diff --git a/api/src/com/cloud/network/NetworkModel.java b/api/src/com/cloud/network/NetworkModel.java index 468feb384c2..9ce024d9950 100644 --- a/api/src/com/cloud/network/NetworkModel.java +++ b/api/src/com/cloud/network/NetworkModel.java @@ -22,8 +22,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; - import com.cloud.dc.Vlan; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -277,6 +275,4 @@ public interface NetworkModel { boolean isNetworkReadyForGc(long networkId); boolean getNetworkEgressDefaultPolicy(Long networkId); - - void checkNetworkPermissions(Account owner, Network network, AccessType accessType); } diff --git a/api/src/com/cloud/user/AccountService.java b/api/src/com/cloud/user/AccountService.java index 6cc86cda3fb..eac8a768497 100755 --- a/api/src/com/cloud/user/AccountService.java +++ b/api/src/com/cloud/user/AccountService.java @@ -103,11 +103,12 @@ public interface AccountService { RoleType getRoleType(Account account); - void checkAccess(Account caller, Domain domain) throws PermissionDeniedException; + void checkAccess(Account account, Domain domain) throws PermissionDeniedException; - void checkAccess(Account caller, AccessType accessType, ControlledEntity... entities) throws PermissionDeniedException; + void checkAccess(Account account, AccessType accessType, boolean sameOwner, ControlledEntity... entities) throws PermissionDeniedException; - void checkAccess(Account caller, AccessType accessType, String apiName, ControlledEntity... entities) throws PermissionDeniedException; + void checkAccess(Account account, AccessType accessType, boolean sameOwner, String apiName, + ControlledEntity... entities) throws PermissionDeniedException; Long finalyzeAccountId(String accountName, Long domainId, Long projectId, boolean enabledOnly); diff --git a/api/src/org/apache/cloudstack/acl/SecurityChecker.java b/api/src/org/apache/cloudstack/acl/SecurityChecker.java index 79366bdc97a..41708717548 100644 --- a/api/src/org/apache/cloudstack/acl/SecurityChecker.java +++ b/api/src/org/apache/cloudstack/acl/SecurityChecker.java @@ -31,10 +31,10 @@ import com.cloud.utils.component.Adapter; public interface SecurityChecker extends Adapter { public enum AccessType { - ListEntry, - UseEntry, - OperateEntry, ModifyProject, + OperateEntry, + UseEntry, + ListEntry } /** diff --git a/api/src/org/apache/cloudstack/api/command/admin/address/AssociateIPAddrCmdByAdmin.java b/api/src/org/apache/cloudstack/api/command/admin/address/AssociateIPAddrCmdByAdmin.java index 494a6d66e40..dbff93f222a 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/address/AssociateIPAddrCmdByAdmin.java +++ b/api/src/org/apache/cloudstack/api/command/admin/address/AssociateIPAddrCmdByAdmin.java @@ -31,11 +31,8 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; -import com.cloud.network.vpc.Vpc; -@APICommand(name = "associateIpAddress", description = "Acquires and associates a public IP to an account.", responseObject = IPAddressResponse.class, responseView = ResponseView.Full, - entityType = {IpAddress.class, Vpc.class}, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) +@APICommand(name = "associateIpAddress", description = "Acquires and associates a public IP to an account.", responseObject = IPAddressResponse.class, responseView = ResponseView.Full) public class AssociateIPAddrCmdByAdmin extends AssociateIPAddrCmd { public static final Logger s_logger = Logger.getLogger(AssociateIPAddrCmdByAdmin.class.getName()); diff --git a/api/src/org/apache/cloudstack/api/command/admin/vm/AddNicToVMCmdByAdmin.java b/api/src/org/apache/cloudstack/api/command/admin/vm/AddNicToVMCmdByAdmin.java index 3dd22c15adb..945f8499fe4 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vm/AddNicToVMCmdByAdmin.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/AddNicToVMCmdByAdmin.java @@ -33,6 +33,7 @@ import org.apache.cloudstack.context.CallContext; import com.cloud.uservm.UserVm; import com.cloud.vm.VirtualMachine; + @APICommand(name = "addNicToVirtualMachine", description = "Adds VM to specified network by creating a NIC", responseObject = UserVmResponse.class, responseView = ResponseView.Full, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class AddNicToVMCmdByAdmin extends AddNicToVMCmd { diff --git a/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java b/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java index 48fe43ee84f..96174e12377 100644 --- a/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java @@ -58,7 +58,6 @@ import com.cloud.projects.Project; import com.cloud.user.Account; @APICommand(name = "associateIpAddress", description = "Acquires and associates a public IP to an account.", responseObject = IPAddressResponse.class, responseView = ResponseView.Restricted, - entityType = {IpAddress.class, Vpc.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(AssociateIPAddrCmd.class.getName()); diff --git a/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java index 6fb120fa8b3..865cd1b7647 100644 --- a/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java @@ -49,6 +49,7 @@ import com.cloud.utils.net.Ip; import com.cloud.utils.net.NetUtils; import com.cloud.vm.VirtualMachine; + @APICommand(name = "createPortForwardingRule", description = "Creates a port forwarding rule", responseObject = FirewallRuleResponse.class, entityType = {FirewallRule.class, VirtualMachine.class, IpAddress.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java index db4d70e685a..dd9adefb6cb 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java @@ -23,11 +23,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import com.cloud.utils.net.NetUtils; import org.apache.log4j.Logger; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; -import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; @@ -41,15 +38,15 @@ import org.apache.cloudstack.context.CallContext; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.utils.StringUtils; +import com.cloud.utils.net.NetUtils; import com.cloud.vm.VirtualMachine; @APICommand(name = "assignToLoadBalancerRule", description = "Assigns virtual machine or a list of virtual machines to a load balancer rule.", - responseObject = SuccessResponse.class, entityType = {FirewallRule.class, VirtualMachine.class}, + responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { @@ -61,7 +58,6 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @ACL(accessType = AccessType.OperateEntry) @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, @@ -69,7 +65,6 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { description = "the ID of the load balancer rule") private Long id; - @ACL(accessType = AccessType.OperateEntry) @Parameter(name = ApiConstants.VIRTUAL_MACHINE_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java index dd031913c10..9905c0b1acc 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java @@ -86,7 +86,7 @@ public class ListLBStickinessPoliciesCmd extends BaseListCmd { if (lb != null) { //check permissions Account caller = CallContext.current().getCallingAccount(); - _accountService.checkAccess(caller, null, lb); + _accountService.checkAccess(caller, null, true, lb); List stickinessPolicies = _lbService.searchForLBStickinessPolicies(this); LBStickinessResponse spResponse = _responseGenerator.createLBStickinessPolicyResponse(stickinessPolicies, lb); spResponses.add(spResponse); @@ -94,7 +94,7 @@ public class ListLBStickinessPoliciesCmd extends BaseListCmd { } response.setResponseName(getCommandName()); - setResponseObject(response); + this.setResponseObject(response); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java index 2a9311e9638..1df77ec0fda 100644 --- a/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java @@ -34,11 +34,8 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; -import com.cloud.network.vpc.Vpc; -import com.cloud.vm.VirtualMachine; @APICommand(name = "disableStaticNat", description = "Disables static rule for given ip address", responseObject = SuccessResponse.class, - entityType = {IpAddress.class, VirtualMachine.class, Vpc.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DisableStaticNatCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeletePortForwardingRuleCmd.class.getName()); @@ -92,7 +89,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); - setResponseObject(response); + this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to disable static nat"); } diff --git a/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java index 9d888760fa9..aa4e28768a6 100644 --- a/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java @@ -18,8 +18,6 @@ package org.apache.cloudstack.api.command.user.nat; import org.apache.log4j.Logger; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; -import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; @@ -35,13 +33,10 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; -import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -import com.cloud.vm.VirtualMachine; @APICommand(name = "enableStaticNat", description = "Enables static nat for given ip address", responseObject = SuccessResponse.class, - entityType = {IpAddress.class, VirtualMachine.class, Vpc.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class EnableStaticNatCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateIpForwardingRuleCmd.class.getName()); @@ -52,12 +47,10 @@ public class EnableStaticNatCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @ACL(accessType = AccessType.OperateEntry) @Parameter(name = ApiConstants.IP_ADDRESS_ID, type = CommandType.UUID, entityType = IPAddressResponse.class, required = true, description = "the public IP " + "address id for which static nat feature is being enabled") private Long ipAddressId; - @ACL(accessType = AccessType.OperateEntry) @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, required = true, description = "the ID of " + "the virtual machine for enabling static nat feature") private Long virtualMachineId; @@ -140,7 +133,7 @@ public class EnableStaticNatCmd extends BaseCmd { boolean result = _rulesService.enableStaticNat(ipAddressId, virtualMachineId, getNetworkId(), getVmSecondaryIp()); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); - setResponseObject(response); + this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to enable static nat"); } diff --git a/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java index bd8662e1460..df7fe8296bc 100644 --- a/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.snapshot; import org.apache.log4j.Logger; -import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandJobType; import org.apache.cloudstack.api.ApiConstants; @@ -63,7 +62,6 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { description = "The domain ID of the snapshot. If used with the account parameter, specifies a domain for the account associated with the disk volume.") private Long domainId; - @ACL @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.UUID, entityType = VolumeResponse.class, required = true, description = "The ID of the disk volume") private Long volumeId; diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/AddNicToVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/AddNicToVMCmd.java index fd30152ae08..f265ecf236a 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/AddNicToVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/AddNicToVMCmd.java @@ -54,7 +54,6 @@ public class AddNicToVMCmd extends BaseAsyncCmd { required=true, description="Virtual Machine ID") private Long vmId; - @ACL @Parameter(name = ApiConstants.NETWORK_ID, type = CommandType.UUID, entityType = NetworkResponse.class, required = true, description = "Network ID") private Long netId; diff --git a/api/src/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java index 1310ba5b759..10ff5cddb12 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.vmsnapshot; import java.util.logging.Logger; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -42,7 +43,7 @@ public class CreateVMSnapshotCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateVMSnapshotCmd.class.getName()); private static final String s_name = "createvmsnapshotresponse"; - @ACL + @ACL(accessType = AccessType.OperateEntry) @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, required = true, entityType = UserVmResponse.class, description = "The ID of the vm") private Long vmId; diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java index ab092030fd6..7c2a3293d57 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java @@ -37,8 +37,7 @@ import com.cloud.storage.Volume; import com.cloud.user.Account; import com.cloud.vm.VirtualMachine; -@APICommand(name = "attachVolume", description = "Attaches a disk volume to a virtual machine.", responseObject = VolumeResponse.class, responseView = ResponseView.Restricted, entityType = { - VirtualMachine.class, Volume.class}, +@APICommand(name = "attachVolume", description = "Attaches a disk volume to a virtual machine.", responseObject = VolumeResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AttachVolumeCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AttachVolumeCmd.class.getName()); @@ -53,7 +52,6 @@ public class AttachVolumeCmd extends BaseAsyncCmd { + "* 4 - /dev/xvde" + "* 5 - /dev/xvdf" + "* 6 - /dev/xvdg" + "* 7 - /dev/xvdh" + "* 8 - /dev/xvdi" + "* 9 - /dev/xvdj") private Long deviceId; - @ACL(accessType = AccessType.OperateEntry) @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = VolumeResponse.class, required = true, description = "the ID of the disk volume") private Long id; diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java index dc912610b48..1e3c01cec9e 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java @@ -19,8 +19,6 @@ package org.apache.cloudstack.api.command.user.volume; import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; -import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandJobType; import org.apache.cloudstack.api.ApiConstants; @@ -93,7 +91,6 @@ public class CreateVolumeCmd extends BaseAsyncCreateCustomIdCmd { @Parameter(name = ApiConstants.MAX_IOPS, type = CommandType.LONG, description = "max iops") private Long maxIops; - @ACL @Parameter(name = ApiConstants.SNAPSHOT_ID, type = CommandType.UUID, entityType = SnapshotResponse.class, @@ -106,7 +103,6 @@ public class CreateVolumeCmd extends BaseAsyncCreateCustomIdCmd { @Parameter(name = ApiConstants.DISPLAY_VOLUME, type = CommandType.BOOLEAN, description = "an optional field, whether to display the volume to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayVolume; - @ACL(accessType = AccessType.OperateEntry) @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, diff --git a/client/pom.xml b/client/pom.xml index b3d857dc222..09daebc88fa 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -226,16 +226,6 @@ cloud-mom-inmemory ${project.version} - - org.apache.cloudstack - cloud-plugin-iam - ${project.version} - - - org.apache.cloudstack - cloud-iam - ${project.version} - org.apache.cloudstack cloud-framework-ipc diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index da3fbfc00dc..d247aa03475 100644 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -732,21 +732,6 @@ listLdapUsers=3 ldapCreateAccount=3 importLdapUsers=3 -### IAM commands -createIAMPolicy=1 -deleteIAMPolicy=1 -listIAMPolicies=1 -addIAMPermissionToIAMPolicy=1 -removeIAMPermissionFromIAMPolicy=1 -createIAMGroup=1 -deleteIAMGroup=1 -listIAMGroups=1 -addAccountToIAMGroup=1 -removeAccountFromIAMGroup=1 -attachIAMPolicyToIAMGroup=1 -removeIAMPolicyFromIAMGroup=1 -attachIAMPolicyToAccount=1 -removeIAMPolicyFromAccount=1 #### juniper-contrail commands createServiceInstance=1 diff --git a/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml b/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml index 0f58d7d35e0..d54823a33ef 100644 --- a/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml +++ b/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml @@ -46,7 +46,7 @@ + value="AffinityGroupAccessChecker,DomainChecker" /> , T, K> { if (_entity == null || _specifiedAttrs == null || _specifiedAttrs.size() != 1) { throw new RuntimeException("Now now, better specify an attribute or else we can't help you"); } - if (_specifiedAttrs.size() > 0) { - return _specifiedAttrs.get(0); - } - // look for attributes from joins - for (JoinBuilder> join : _joins.values()) { - SearchBase sb = join.getT(); - if (sb.getSpecifiedAttribute() != null) { - return sb.getSpecifiedAttribute(); - } - } - throw new CloudRuntimeException("Unable to find any specified attributes. You sure you know what you're doing?"); + return _specifiedAttrs.get(0); } protected List getSpecifiedAttributes() { diff --git a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java index a7943905c04..8b5b3e0b02f 100644 --- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java +++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java @@ -27,12 +27,11 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; - import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.lb.ApplicationLoadBalancerRuleVO; import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -522,7 +521,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In return true; } - _accountMgr.checkAccess(caller, null, internalLbVm); + _accountMgr.checkAccess(caller, null, true, internalLbVm); _itMgr.expunge(internalLbVm.getUuid()); _internalLbVmDao.remove(internalLbVm.getId()); @@ -537,7 +536,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In } //check permissions - _accountMgr.checkAccess(caller, null, internalLbVm); + _accountMgr.checkAccess(caller, null, true, internalLbVm); return stopInternalLbVm(internalLbVm, forced, caller, callerUserId); } @@ -915,7 +914,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In } //check permissions - _accountMgr.checkAccess(caller, null, internalLbVm); + _accountMgr.checkAccess(caller, null, true, internalLbVm); return startInternalLbVm(internalLbVm, caller, callerUserId, null); } diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java index a39fb434b0b..1a29f9c529b 100644 --- a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java @@ -34,6 +34,7 @@ import org.apache.cloudstack.api.command.admin.user.RegisterCmd; import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; import org.apache.cloudstack.context.CallContext; +import com.cloud.api.query.vo.ControlledViewEntity; import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.dao.ResourceCountDao; import com.cloud.domain.Domain; @@ -100,6 +101,11 @@ public class MockAccountManager extends ManagerBase implements AccountManager { return null; } + @Override + public void checkAccess(Account arg0, AccessType arg1, boolean arg2, ControlledEntity... arg3) throws PermissionDeniedException { + // TODO Auto-generated method stub + } + @Override public String[] createApiKeyAndSecretKey(RegisterCmd arg0) { // TODO Auto-generated method stub @@ -202,19 +208,7 @@ public class MockAccountManager extends ManagerBase implements AccountManager { } - @Override - public void buildACLSearchBuilder(SearchBuilder sb, boolean isRecursive, List permittedDomains, List permittedAccounts, - List permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria) { - // TODO Auto-generated method stub - } - - @Override - public void buildACLSearchCriteria(SearchCriteria sc, boolean isRecursive, List permittedDomains, List permittedAccounts, - List permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria) { - // TODO Auto-generated method stub - - } @Override public void buildACLViewSearchCriteria(SearchCriteria sc, SearchCriteria aclSc, boolean isRecursive, @@ -247,6 +241,57 @@ public class MockAccountManager extends ManagerBase implements AccountManager { return null; } + @Override + public void buildACLSearchBuilder( + SearchBuilder arg0, Long arg1, + boolean arg2, List arg3, ListProjectResourcesCriteria arg4) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLSearchCriteria( + SearchCriteria arg0, Long arg1, + boolean arg2, List arg3, ListProjectResourcesCriteria arg4) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLSearchParameters(Account arg0, Long arg1, String arg2, + Long arg3, List arg4, + Ternary arg5, + boolean arg6, boolean arg7) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria, List grantedIds, List revokedIds) { + // TODO Auto-generated method stub + } + + @Override + public void buildACLViewSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLViewSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria, List grantedIds, List revokedIds) { + // TODO Auto-generated method stub + + } @Override public Long checkAccessAndSpecifyAuthority(Account arg0, Long arg1) { @@ -362,24 +407,15 @@ public class MockAccountManager extends ManagerBase implements AccountManager { } + @Override + public void checkAccess(Account account, AccessType accessType, boolean sameOwner, String apiName, + ControlledEntity... entities) throws PermissionDeniedException { + // TODO Auto-generated method stub + } @Override public Long finalyzeAccountId(String accountName, Long domainId, Long projectId, boolean enabledOnly) { // TODO Auto-generated method stub return null; } - - @Override - public void checkAccess(Account account, AccessType accessType, ControlledEntity... entities) throws PermissionDeniedException { - // TODO Auto-generated method stub - - } - - @Override - public void checkAccess(Account account, AccessType accessType, String apiName, ControlledEntity... entities) throws PermissionDeniedException { - // TODO Auto-generated method stub - - } - - } diff --git a/server/src/com/cloud/acl/DomainChecker.java b/server/src/com/cloud/acl/DomainChecker.java index 9ee65db9355..729a0d1e2ab 100755 --- a/server/src/com/cloud/acl/DomainChecker.java +++ b/server/src/com/cloud/acl/DomainChecker.java @@ -19,7 +19,6 @@ package com.cloud.acl; import javax.ejb.Local; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.apache.cloudstack.acl.ControlledEntity; @@ -51,8 +50,6 @@ import com.cloud.utils.component.AdapterBase; @Local(value = SecurityChecker.class) public class DomainChecker extends AdapterBase implements SecurityChecker { - public static final Logger s_logger = Logger.getLogger(DomainChecker.class); - @Inject DomainDao _domainDao; @Inject @@ -104,15 +101,6 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { @Override public boolean checkAccess(Account caller, ControlledEntity entity, AccessType accessType) throws PermissionDeniedException { - - if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountService.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 true; - } - if (entity instanceof VirtualMachineTemplate) { VirtualMachineTemplate template = (VirtualMachineTemplate)entity; @@ -344,15 +332,20 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { if (action != null && ("SystemCapability".equals(action))) { if (caller != null && caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { return true; + } else { + return false; } - } else if (action != null && ("DomainCapability".equals(action))) { if (caller != null && caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { return true; + } else { + return false; } } else if (action != null && ("DomainResourceCapability".equals(action))) { if (caller != null && caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { return true; + } else { + return false; } } return checkAccess(caller, entity, accessType); diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index b6b9b2915aa..3447662b2bd 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -23,6 +23,10 @@ import javax.inject.Inject; import org.apache.log4j.Logger; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseAsyncCreateCmd; @@ -36,6 +40,7 @@ import org.apache.cloudstack.framework.jobs.AsyncJobManager; import com.cloud.api.dispatch.DispatchChain; import com.cloud.api.dispatch.DispatchChainFactory; import com.cloud.api.dispatch.DispatchTask; +import com.cloud.user.Account; import com.cloud.user.AccountManager; public class ApiDispatcher { @@ -74,6 +79,23 @@ public class ApiDispatcher { asyncCreationDispatchChain.dispatch(new DispatchTask(cmd, params)); } + private void doAccessChecks(BaseCmd cmd, Map entitiesToAccess) { + Account caller = CallContext.current().getCallingAccount(); + + APICommand commandAnnotation = cmd.getClass().getAnnotation(APICommand.class); + String apiName = commandAnnotation != null ? commandAnnotation.name() : null; + + if (!entitiesToAccess.isEmpty()) { + for (Object entity : entitiesToAccess.keySet()) { + if (entity instanceof ControlledEntity) { + _accountMgr.checkAccess(caller, entitiesToAccess.get(entity), false, apiName, (ControlledEntity) entity); + } else if (entity instanceof InfrastructureEntity) { + //FIXME: Move this code in adapter, remove code from Account manager + } + } + } + } + public void dispatch(final BaseCmd cmd, final Map params, final boolean execute) throws Exception { // Let the chain of responsibility dispatch gradually standardDispatchChain.dispatch(new DispatchTask(cmd, params)); diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 3ec5abc3e9d..2a3c16408d2 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -1587,7 +1587,7 @@ public class ApiResponseHelper implements ResponseGenerator { throw new PermissionDeniedException("Account " + caller + " is not authorized to see job id=" + job.getId()); } } else if (_accountMgr.isDomainAdmin(caller.getId())) { - _accountMgr.checkAccess(caller, null, jobOwner); + _accountMgr.checkAccess(caller, null, true, jobOwner); } return createAsyncJobResponse(_jobMgr.queryJob(cmd.getId(), true)); diff --git a/server/src/com/cloud/api/dispatch/ParamProcessWorker.java b/server/src/com/cloud/api/dispatch/ParamProcessWorker.java index ba5bebff641..0bb02200392 100644 --- a/server/src/com/cloud/api/dispatch/ParamProcessWorker.java +++ b/server/src/com/cloud/api/dispatch/ParamProcessWorker.java @@ -40,7 +40,6 @@ import org.apache.cloudstack.acl.InfrastructureEntity; import org.apache.cloudstack.acl.SecurityChecker; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; -import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; @@ -56,11 +55,7 @@ import org.apache.cloudstack.api.command.user.event.DeleteEventsCmd; import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import org.apache.cloudstack.context.CallContext; -import com.cloud.dc.DataCenter; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; -import com.cloud.offering.DiskOffering; -import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.utils.DateUtil; @@ -222,113 +217,29 @@ public class ParamProcessWorker implements DispatchWorker { } - private void doAccessChecks(final BaseCmd cmd, final Map entitiesToAccess) { + private void doAccessChecks(BaseCmd cmd, Map entitiesToAccess) { Account caller = CallContext.current().getCallingAccount(); - Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); - if (owner == null) { - owner = caller; - } + Account owner = _accountMgr.getActiveAccountById(cmd.getEntityOwnerId()); if (cmd instanceof BaseAsyncCreateCmd) { - if (owner.getId() != caller.getId()) { - // mimic impersonation either by passing (account, domainId) or through derived owner from other api parameters - // in this case, we should check access using the owner - _accountMgr.checkAccess(caller, null, owner); - } - } else { - // check access using the caller for other operational cmds - owner = caller; + // check that caller can access the owner account. + _accountMgr.checkAccess(caller, null, true, owner); } - APICommand commandAnnotation = cmd.getClass().getAnnotation(APICommand.class); - - String apiName = commandAnnotation != null ? commandAnnotation.name() : null; - if (!entitiesToAccess.isEmpty()) { - List entitiesToOperate = new ArrayList(); + // check that caller can access the owner account. + _accountMgr.checkAccess(caller, null, true, owner); for (Object entity : entitiesToAccess.keySet()) { if (entity instanceof ControlledEntity) { - - if (AccessType.OperateEntry == entitiesToAccess.get(entity)) { - entitiesToOperate.add((ControlledEntity) entity); - } else { - _accountMgr.checkAccess(owner, entitiesToAccess.get(entity), apiName, - (ControlledEntity) entity); - } + _accountMgr.checkAccess(caller, entitiesToAccess.get(entity), true, (ControlledEntity) entity); } else if (entity instanceof InfrastructureEntity) { - if (entity instanceof DataCenter) { - checkZoneAccess(owner, (DataCenter)entity); - } else if (entity instanceof ServiceOffering) { - checkServiceOfferingAccess(owner, (ServiceOffering)entity); - } else if (entity instanceof DiskOffering) { - checkDiskOfferingAccess(owner, (DiskOffering)entity); - } + // FIXME: Move this code in adapter, remove code from + // Account manager } } - - if (!entitiesToOperate.isEmpty()) { - _accountMgr.checkAccess(owner, AccessType.OperateEntry, apiName, - entitiesToOperate.toArray(new ControlledEntity[entitiesToOperate.size()])); - } - } } - private void checkDiskOfferingAccess(Account caller, DiskOffering dof) { - for (SecurityChecker checker : _secChecker) { - if (checker.checkAccess(caller, dof)) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Access granted to " + caller + " to disk offering:" + dof.getId() + " by " - + checker.getName()); - } - return; - } else { - throw new PermissionDeniedException("Access denied to " + caller + " by " + checker.getName()); - } - } - - assert false : "How can all of the security checkers pass on checking this caller?"; - throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to disk offering:" - + dof.getId()); - } - - private void checkServiceOfferingAccess(Account caller, ServiceOffering sof) { - for (SecurityChecker checker : _secChecker) { - if (checker.checkAccess(caller, sof)) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Access granted to " + caller + " to service offering:" + sof.getId() + " by " - + checker.getName()); - } - return; - } else { - throw new PermissionDeniedException("Access denied to " + caller + " by " + checker.getName()); - } - } - - assert false : "How can all of the security checkers pass on checking this caller?"; - throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to service offering:" - + sof.getId()); - } - - private void checkZoneAccess(Account caller, DataCenter zone) { - for (SecurityChecker checker : _secChecker) { - if (checker.checkAccess(caller, zone)) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Access granted to " + caller + " to zone:" + zone.getId() + " by " - + checker.getName()); - } - return; - } else { - throw new PermissionDeniedException("Access denied to " + caller + " by " + checker.getName() - + " for zone " + zone.getId()); - } - } - - assert false : "How can all of the security checkers pass on checking this caller?"; - throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to zone:" - + zone.getId()); - } - @SuppressWarnings({"unchecked", "rawtypes"}) private void setFieldValue(final Field field, final BaseCmd cmdObj, final Object paramObj, final Parameter annotation) throws IllegalArgumentException, ParseException { try { diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java index a2437b8900d..e675e83b9b9 100644 --- a/server/src/com/cloud/api/query/QueryManagerImpl.java +++ b/server/src/com/cloud/api/query/QueryManagerImpl.java @@ -478,9 +478,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { private Pair, Integer> searchForEventsInternal(ListEventsCmd cmd) { Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Long id = cmd.getId(); String type = cmd.getType(); @@ -493,14 +491,16 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { Ternary domainIdRecursiveListProject = new Ternary( cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, cmd.listAll(), false, "listEvents"); - //Long domainId = domainIdRecursiveListProject.first(); + _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(EventJoinVO.class, "createDate", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _eventJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("levelL", sb.entity().getLevel(), SearchCriteria.Op.LIKE); @@ -516,9 +516,9 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { sb.and("archived", sb.entity().getArchived(), SearchCriteria.Op.EQ); SearchCriteria sc = sb.create(); - SearchCriteria aclSc = _eventJoinDao.createSearchCriteria(); - // building ACL search criteria - _accountMgr.buildACLViewSearchCriteria(sc, aclSc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + // building ACL condition + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); // For end users display only enabled events if (!_accountMgr.isRootAdmin(caller.getId())) { @@ -597,9 +597,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { private Pair, Integer> listTagsInternal(ListTagsCmd cmd) { Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); String key = cmd.getKey(); String value = cmd.getValue(); String resourceId = cmd.getResourceId(); @@ -610,14 +608,16 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, listAll, false, "listTags"); + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, + domainIdRecursiveListProject, listAll, false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(ResourceTagJoinVO.class, "resourceType", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _resourceTagJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); sb.and("key", sb.entity().getKey(), SearchCriteria.Op.EQ); sb.and("value", sb.entity().getValue(), SearchCriteria.Op.EQ); @@ -633,9 +633,8 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { // now set the SC criteria... SearchCriteria sc = sb.create(); - SearchCriteria aclSc = _resourceTagJoinDao.createSearchCriteria(); - // building ACL search criteria - _accountMgr.buildACLViewSearchCriteria(sc, aclSc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); if (key != null) { sc.setParameters("key", key); @@ -677,29 +676,28 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { String keyword = cmd.getKeyword(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary( cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, cmd.listAll(), false, "listInstanceGroups"); - // Long domainId = domainIdRecursiveListProject.first(); + _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(InstanceGroupJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _vmGroupJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); SearchCriteria sc = sb.create(); - SearchCriteria aclSc = _vmGroupJoinDao.createSearchCriteria(); - // building ACL search criteria - _accountMgr.buildACLViewSearchCriteria(sc, aclSc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); if (keyword != null) { @@ -996,9 +994,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { String securityGroup = cmd.getSecurityGroupName(); Long id = cmd.getId(); Object keyword = cmd.getKeyword(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Map tags = cmd.getTags(); if (instanceId != null) { @@ -1006,14 +1002,14 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { if (userVM == null) { throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance " + instanceId + "; instance not found."); } - _accountMgr.checkAccess(caller, null, userVM); + _accountMgr.checkAccess(caller, null, true, userVM); return listSecurityGroupRulesByVM(instanceId.longValue(), cmd.getStartIndex(), cmd.getPageSizeVal()); } Ternary domainIdRecursiveListProject = new Ternary( cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, cmd.listAll(), false, "listSecurityGroups"); + _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(); @@ -1022,13 +1018,15 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { SearchBuilder sb = _securityGroupJoinDao.createSearchBuilder(); sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct // ids + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); SearchCriteria sc = sb.create(); - SearchCriteria aclSc = _securityGroupJoinDao.createSearchCriteria(); - // building ACL search criteria - _accountMgr.buildACLViewSearchCriteria(sc, aclSc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); if (id != null) { sc.setParameters("id", id); @@ -1120,19 +1118,12 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { Long podId, Long clusterId, Long hostId, String keyword, Long networkId, Long vpcId, Boolean forVpc, String role, String version) { Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary( cmd.getDomainId(), cmd.isRecursive(), null); - String action = "listRouters"; - if (cmd instanceof ListInternalLBVMsCmd) { - action = "listInternalLoadBalancerVMs"; - } - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, cmd.listAll(), false, action); - + _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(); @@ -1145,6 +1136,8 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { // number of // records with // pagination + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); sb.and("name", sb.entity().getInstanceName(), SearchCriteria.Op.LIKE); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); @@ -1171,9 +1164,8 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { } SearchCriteria sc = sb.create(); - SearchCriteria aclSc = _routerJoinDao.createSearchCriteria(); - // building ACL search criteria - _accountMgr.buildACLViewSearchCriteria(sc, aclSc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); if (keyword != null) { SearchCriteria ssc = _routerJoinDao.createSearchCriteria(); @@ -1406,21 +1398,20 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { boolean listAll = cmd.listAll(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary( domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, listAll, true, "listProjectInvitations"); - //domainId = domainIdRecursiveListProject.first(); - + _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, + domainIdRecursiveListProject, listAll, true); + domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(ProjectInvitationJoinVO.class, "id", true, startIndex, pageSizeVal); SearchBuilder sb = _projectInvitationJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); sb.and("projectId", sb.entity().getProjectId(), SearchCriteria.Op.EQ); sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); @@ -1428,9 +1419,8 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); SearchCriteria sc = sb.create(); - SearchCriteria aclSc = _projectInvitationJoinDao.createSearchCriteria(); - // building ACL search criteria - _accountMgr.buildACLViewSearchCriteria(sc, aclSc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, + listProjectResourcesCriteria); if (projectId != null) { sc.setParameters("projectId", projectId); @@ -1835,19 +1825,53 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { private Pair, Integer> searchForAccountsInternal(ListAccountsCmd cmd) { Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); - List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); - - boolean listAll = cmd.listAll(); - Long id = cmd.getId(); + Long domainId = cmd.getDomainId(); + Long accountId = cmd.getId(); String accountName = cmd.getSearchName(); - Ternary domainIdRecursiveListProject = new Ternary( - cmd.getDomainId(), cmd.isRecursive(), null); - // ListAccountsCmd is not BaseListAccountResourcesCmd, so no (domainId, accountName) combination - _accountMgr.buildACLSearchParameters(caller, id, null, null, permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, listAll, false, "listAccounts"); - Boolean isRecursive = domainIdRecursiveListProject.second(); + boolean isRecursive = cmd.isRecursive(); + boolean listAll = cmd.listAll(); + Boolean listForDomain = false; + + if (accountId != null) { + Account account = _accountDao.findById(accountId); + if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { + throw new InvalidParameterValueException("Unable to find account by id " + accountId); + } + + _accountMgr.checkAccess(caller, null, true, account); + } + + if (domainId != null) { + Domain domain = _domainDao.findById(domainId); + if (domain == null) { + throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist"); + } + + _accountMgr.checkAccess(caller, domain); + + if (accountName != null) { + Account account = _accountDao.findActiveAccount(accountName, domainId); + if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { + throw new InvalidParameterValueException("Unable to find account by name " + accountName + + " in domain " + domainId); + } + _accountMgr.checkAccess(caller, null, true, account); + } + } + + if (accountId == null) { + if (_accountMgr.isAdmin(caller.getId()) && listAll && domainId == null) { + listForDomain = true; + isRecursive = true; + if (domainId == null) { + domainId = caller.getDomainId(); + } + } else if (_accountMgr.isAdmin(caller.getId()) && domainId != null) { + listForDomain = true; + } else { + accountId = caller.getAccountId(); + } + } Filter searchFilter = new Filter(AccountJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -1858,6 +1882,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { SearchBuilder sb = _accountJoinDao.createSearchBuilder(); sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ); + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); @@ -1865,32 +1890,12 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { sb.and("typeNEQ", sb.entity().getType(), SearchCriteria.Op.NEQ); sb.and("idNEQ", sb.entity().getId(), SearchCriteria.Op.NEQ); - SearchCriteria sc = sb.create(); - SearchCriteria aclSc = _accountJoinDao.createSearchCriteria(); - // building ACL search criteria. Here we cannot use the common accountMgr.buildACLViewSearchCriteria because - // 1) AccountJoinVO does not have accountId field, permittedAccounts correspond to list of resource ids. - // 2) AccountJoinVO use type not accountType field to indicate its type - if (!permittedDomains.isEmpty() || !permittedAccounts.isEmpty() || !permittedResources.isEmpty()) { - if (!permittedDomains.isEmpty()) { - if (isRecursive) { - for (int i = 0; i < permittedDomains.size(); i++) { - Domain domain = _domainDao.findById(permittedDomains.get(i)); - aclSc.addOr("domainPath", SearchCriteria.Op.LIKE, domain.getPath() + "%"); - } - } else { - aclSc.addOr("domainId", SearchCriteria.Op.IN, permittedDomains.toArray()); - } - } - if (!permittedAccounts.isEmpty()) { - aclSc.addOr("id", SearchCriteria.Op.IN, permittedAccounts.toArray()); - } - if (!permittedResources.isEmpty()) { - aclSc.addOr("id", SearchCriteria.Op.IN, permittedResources.toArray()); - } - - sc.addAnd("id", SearchCriteria.Op.SC, aclSc); + if (listForDomain && isRecursive) { + sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); } + SearchCriteria sc = sb.create(); + sc.setParameters("idNEQ", Account.ACCOUNT_ID_SYSTEM); if (keyword != null) { @@ -1917,10 +1922,19 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { } // don't return account of type project to the end user - sc.setParameters("typeNEQ", Account.ACCOUNT_TYPE_PROJECT); + sc.setParameters("typeNEQ", 5); - if (id != null) { - sc.setParameters("id", id); + if (accountId != null) { + sc.setParameters("id", accountId); + } + + if (listForDomain) { + if (isRecursive) { + Domain domain = _domainDao.findById(domainId); + sc.setParameters("path", domain.getPath() + "%"); + } else { + sc.setParameters("domainId", domainId); + } } return _accountJoinDao.searchAndCount(sc, searchFilter); @@ -1939,20 +1953,17 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary( cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, - cmd.listAll(), false, "listAsyncJobs"); + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, + domainIdRecursiveListProject, cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(AsyncJobJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - /* SearchBuilder sb = _jobJoinDao.createSearchBuilder(); sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); boolean accountJoinIsDone = false; @@ -1976,7 +1987,8 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { } } - + Object keyword = cmd.getKeyword(); + Object startDate = cmd.getStartDate(); SearchCriteria sc = sb.create(); if (listProjectResourcesCriteria != null) { @@ -1993,17 +2005,6 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { sc.setParameters("domainId", domainId); } } - */ - - Object keyword = cmd.getKeyword(); - Object startDate = cmd.getStartDate(); - - // populate the search criteria with the values passed in - SearchCriteria sc = _jobJoinDao.createSearchCriteria(); - SearchCriteria aclSc = _jobJoinDao.createSearchCriteria(); - - // building ACL search criteria - _accountMgr.buildACLViewSearchCriteria(sc, aclSc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); if (keyword != null) { sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -2466,7 +2467,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { throw ex; } - _accountMgr.checkAccess(caller, null, vmInstance); + _accountMgr.checkAccess(caller, null, true, vmInstance); ServiceOfferingVO offering = _srvOfferingDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId()); sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId()); @@ -2806,366 +2807,6 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { return response; } - // Temporarily disable this method which used IAM model to do template list - private Pair, Integer> searchForTemplatesInternalIAM(ListTemplatesCmd cmd) { - TemplateFilter templateFilter = TemplateFilter.valueOf(cmd.getTemplateFilter()); - Long id = cmd.getId(); - Map tags = cmd.getTags(); - boolean showRemovedTmpl = cmd.getShowRemoved(); - Account caller = CallContext.current().getCallingAccount(); - - // TODO: listAll flag has some conflicts with TemplateFilter parameter - boolean listAll = false; - if (templateFilter != null && templateFilter == TemplateFilter.all) { - if (_accountMgr.isNormalUser(caller.getId())) { - throw new InvalidParameterValueException("Filter " + TemplateFilter.all - + " can be specified by admin only"); - } - listAll = true; - } - - List permittedDomains = new ArrayList(); - List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary( - cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, listAll, false, "listTemplates"); - - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured)); - HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); - - return searchForTemplatesInternalIAM(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, - cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, showDomr, - cmd.listInReadyState(), permittedDomains, permittedAccounts, permittedResources, isRecursive, caller, listProjectResourcesCriteria, tags, showRemovedTmpl); - } - - // Temporarily disable this method which used IAM model to do template list - private Pair, Integer> searchForTemplatesInternalIAM(Long templateId, String name, - String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long pageSize, - Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady, - List permittedDomains, List permittedAccounts, List permittedResources, boolean isRecursive, Account caller, - ListProjectResourcesCriteria listProjectResourcesCriteria, - Map tags, boolean showRemovedTmpl) { - - // check if zone is configured, if not, just return empty list - List hypers = null; - if (!isIso) { - hypers = _resourceMgr.listAvailHypervisorInZone(null, null); - if (hypers == null || hypers.isEmpty()) { - return new Pair, Integer>(new ArrayList(), 0); - } - } - - VMTemplateVO template = null; - - Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); - isAscending = (isAscending == null ? true : isAscending); - Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", isAscending, startIndex, pageSize); - - SearchBuilder sb = _templateJoinDao.createSearchBuilder(); - sb.select(null, Func.DISTINCT, sb.entity().getTempZonePair()); // select distinct (templateId, zoneId) pair - SearchCriteria sc = sb.create(); - - // verify templateId parameter and specially handle it - if (templateId != null) { - template = _templateDao.findByIdIncludingRemoved(templateId); // Done for backward compatibility - Bug-5221 - if (template == null) { - throw new InvalidParameterValueException("Please specify a valid template ID."); - }// If ISO requested then it should be ISO. - if (isIso && template.getFormat() != ImageFormat.ISO) { - s_logger.error("Template Id " + templateId + " is not an ISO"); - InvalidParameterValueException ex = new InvalidParameterValueException("Specified Template Id is not an ISO"); - ex.addProxyObject(template.getUuid(), "templateId"); - throw ex; - }// If ISO not requested then it shouldn't be an ISO. - if (!isIso && template.getFormat() == ImageFormat.ISO) { - s_logger.error("Incorrect format of the template id " + templateId); - InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the specified template id"); - ex.addProxyObject(template.getUuid(), "templateId"); - throw ex; - } - - // if template is not public, perform permission check here - if (!template.isPublicTemplate() && !_accountMgr.isRootAdmin(caller.getId())) { - Account owner = _accountMgr.getAccount(template.getAccountId()); - _accountMgr.checkAccess(caller, null, owner); - } - - // if templateId is specified, then we will just use the id to - // search and ignore other query parameters - sc.addAnd("id", SearchCriteria.Op.EQ, templateId); - } else { - if (!isIso) { - // add hypervisor criteria for template case - if (hypers != null && !hypers.isEmpty()) { - String[] relatedHypers = new String[hypers.size()]; - for (int i = 0; i < hypers.size(); i++) { - relatedHypers[i] = hypers.get(i).toString(); - } - sc.addAnd("hypervisorType", SearchCriteria.Op.IN, relatedHypers); - } - } - - // control different template filters - DomainVO callerDomain = _domainDao.findById(caller.getDomainId()); - if (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community) { - sc.addAnd("publicTemplate", SearchCriteria.Op.EQ, true); - if (templateFilter == TemplateFilter.featured) { - sc.addAnd("featured", SearchCriteria.Op.EQ, true); - } else { - sc.addAnd("featured", SearchCriteria.Op.EQ, false); - } - - /* We don't need this any more to check domain id, based on CLOUDSTACK-5987 - // for public templates, we should get all public templates from all domains in the system - // get all parent domain ID's all the way till root domain - List domainTree = new ArrayList(); - DomainVO domainTreeNode = _domainDao.findById(Domain.ROOT_DOMAIN); // fix for CLOUDSTACK-5987 - domainTree.add(domainTreeNode.getId()); - - // get all child domain ID's under root - List allChildDomains = _domainDao.findAllChildren(domainTreeNode.getPath(), domainTreeNode.getId()); - for (DomainVO childDomain : allChildDomains) { - domainTree.add(childDomain.getId()); - } - - SearchCriteria scc = _templateJoinDao.createSearchCriteria(); - scc.addOr("domainId", SearchCriteria.Op.IN, domainTree.toArray()); - scc.addOr("domainId", SearchCriteria.Op.NULL); - sc.addAnd("domainId", SearchCriteria.Op.SC, scc); - */ - } else if (templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) { - if (permittedDomains.contains(caller.getDomainId())) { - // this caller acts like a domain admin - - sc.addAnd("domainPath", SearchCriteria.Op.LIKE, callerDomain.getPath() + "%"); - } else { - // only display templates owned by caller for resource owner only - sc.addAnd("accountId", SearchCriteria.Op.EQ, caller.getAccountId()); - } - } else if (templateFilter == TemplateFilter.sharedexecutable || templateFilter == TemplateFilter.shared) { - // exclude the caller, only include those granted and not owned by self - permittedDomains.remove(caller.getDomainId()); - permittedAccounts.remove(caller.getAccountId()); - for (Long tid : permittedResources) { - // remove it if it is owned by the caller - VMTemplateVO tmpl = _templateDao.findById(tid); - if (tmpl != null && tmpl.getAccountId() == caller.getAccountId()) { - permittedResources.remove(tid); - } - } - // building ACL search criteria - SearchCriteria aclSc = _templateJoinDao.createSearchCriteria(); - _accountMgr.buildACLViewSearchCriteria(sc, aclSc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); - } else if (templateFilter == TemplateFilter.executable) { - // public template + self template - SearchCriteria scc = _templateJoinDao.createSearchCriteria(); - scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true); - // plus self owned templates or domain tree templates for domain admin - if (permittedDomains.contains(caller.getDomainId())) { - // this caller acts like a domain admin - sc.addOr("domainPath", SearchCriteria.Op.LIKE, callerDomain.getPath() + "%"); - } else { - // only display templates owned by caller for resource owner only - sc.addOr("accountId", SearchCriteria.Op.EQ, caller.getAccountId()); - } - sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc); - } - - // add tags criteria - if (tags != null && !tags.isEmpty()) { - SearchCriteria scc = _templateJoinDao.createSearchCriteria(); - for (String key : tags.keySet()) { - SearchCriteria scTag = _templateJoinDao.createSearchCriteria(); - scTag.addAnd("tagKey", SearchCriteria.Op.EQ, key); - scTag.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key)); - if (isIso) { - scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, ResourceObjectType.ISO); - } else { - scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, ResourceObjectType.Template); - } - scc.addOr("tagKey", SearchCriteria.Op.SC, scTag); - } - sc.addAnd("tagKey", SearchCriteria.Op.SC, scc); - } - - // other criteria - - if (keyword != null) { - sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - } else if (name != null) { - sc.addAnd("name", SearchCriteria.Op.EQ, name); - } - - if (isIso) { - sc.addAnd("format", SearchCriteria.Op.EQ, "ISO"); - - } else { - sc.addAnd("format", SearchCriteria.Op.NEQ, "ISO"); - } - - if (!hyperType.equals(HypervisorType.None)) { - sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hyperType); - } - - if (bootable != null) { - sc.addAnd("bootable", SearchCriteria.Op.EQ, bootable); - } - - if (onlyReady) { - SearchCriteria readySc = _templateJoinDao.createSearchCriteria(); - readySc.addOr("state", SearchCriteria.Op.EQ, TemplateState.Ready); - readySc.addOr("format", SearchCriteria.Op.EQ, ImageFormat.BAREMETAL); - SearchCriteria isoPerhostSc = _templateJoinDao.createSearchCriteria(); - isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO); - isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST); - readySc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc); - sc.addAnd("state", SearchCriteria.Op.SC, readySc); - } - - if (!showDomr) { - // excluding system template - sc.addAnd("templateType", SearchCriteria.Op.NEQ, Storage.TemplateType.SYSTEM); - } - } - - if (zoneId != null) { - SearchCriteria zoneSc = _templateJoinDao.createSearchCriteria(); - zoneSc.addOr("dataCenterId", SearchCriteria.Op.EQ, zoneId); - zoneSc.addOr("dataStoreScope", SearchCriteria.Op.EQ, ScopeType.REGION); - // handle the case where xs-tools.iso and vmware-tools.iso do not - // have data_center information in template_view - SearchCriteria isoPerhostSc = _templateJoinDao.createSearchCriteria(); - isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO); - isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST); - zoneSc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc); - sc.addAnd("dataCenterId", SearchCriteria.Op.SC, zoneSc); - } - - // don't return removed template, this should not be needed since we - // changed annotation for removed field in TemplateJoinVO. - // sc.addAnd("removed", SearchCriteria.Op.NULL); - - // search unique templates and find details by Ids - Pair, Integer> uniqueTmplPair = null; - if(showRemovedTmpl){ - uniqueTmplPair = _templateJoinDao.searchIncludingRemovedAndCount(sc, searchFilter); - } else { - sc.addAnd("templateState", SearchCriteria.Op.EQ, State.Active); - uniqueTmplPair = _templateJoinDao.searchAndCount(sc, searchFilter); - } - - Integer count = uniqueTmplPair.second(); - if (count.intValue() == 0) { - // empty result - return uniqueTmplPair; - } - List uniqueTmpls = uniqueTmplPair.first(); - String[] tzIds = new String[uniqueTmpls.size()]; - int i = 0; - for (TemplateJoinVO v : uniqueTmpls) { - tzIds[i++] = v.getTempZonePair(); - } - List vrs = _templateJoinDao.searchByTemplateZonePair(showRemovedTmpl, tzIds); - return new Pair, Integer>(vrs, count); - - // TODO: revisit the special logic for iso search in - // VMTemplateDaoImpl.searchForTemplates and understand why we need to - // specially handle ISO. The original logic is very twisted and no idea - // about what the code was doing. - - } - - // This method should only be used for keeping old listTemplates and listAffinityGroups behavior, PLEASE DON'T USE IT FOR USE LIST APIs - private void buildTemplateAffinityGroupSearchParameters(Account caller, Long id, String accountName, Long projectId, List - permittedAccounts, Ternary 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 - _accountMgr.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) { - _accountMgr.checkAccess(caller, null, 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 (_accountMgr.isNormalUser(caller.getId())) { - 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 (_accountMgr.isNormalUser(caller.getId())) { - permittedAccounts.add(caller.getId()); - } else if (!listAll) { - if (id == null) { - permittedAccounts.add(caller.getId()); - } else if (!_accountMgr.isRootAdmin(caller.getId())) { - domainIdRecursiveListProject.first(caller.getDomainId()); - domainIdRecursiveListProject.second(true); - } - } else if (domainId == null) { - if (_accountMgr.isDomainAdmin(caller.getId())) { - domainIdRecursiveListProject.first(caller.getDomainId()); - domainIdRecursiveListProject.second(true); - } - } - } else if (domainId != null) { - if (_accountMgr.isNormalUser(caller.getId())) { - permittedAccounts.add(caller.getId()); - } - } - } - } private Pair, Integer> searchForTemplatesInternal(ListTemplatesCmd cmd) { TemplateFilter templateFilter = TemplateFilter.valueOf(cmd.getTemplateFilter()); @@ -3186,7 +2827,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { List permittedAccountIds = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary( cmd.getDomainId(), cmd.isRecursive(), null); - buildTemplateAffinityGroupSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); List permittedAccounts = new ArrayList(); @@ -3251,7 +2892,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { // if template is not public, perform permission check here if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { Account owner = _accountMgr.getAccount(template.getAccountId()); - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, true, owner); } // if templateId is specified, then we will just use the id to @@ -3263,7 +2904,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { if (!permittedAccounts.isEmpty()) { domain = _domainDao.findById(permittedAccounts.get(0).getDomainId()); } else { - domain = _domainDao.findById(DomainVO.ROOT_DOMAIN); + domain = _domainDao.findById(Domain.ROOT_DOMAIN); } // List hypers = null; @@ -3496,7 +3137,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { List permittedAccountIds = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary( cmd.getDomainId(), cmd.isRecursive(), null); - buildTemplateAffinityGroupSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); List permittedAccounts = new ArrayList(); @@ -3511,43 +3152,6 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags, showRemovedISO); } - private Pair, Integer> searchForIsosInternalIAM(ListIsosCmd cmd) { - TemplateFilter isoFilter = TemplateFilter.valueOf(cmd.getIsoFilter()); - Long id = cmd.getId(); - Map tags = cmd.getTags(); - boolean showRemovedISO = cmd.getShowRemoved(); - Account caller = CallContext.current().getCallingAccount(); - - boolean listAll = false; - if (isoFilter != null && isoFilter == TemplateFilter.all) { - if (_accountMgr.isNormalUser(caller.getId())) { - throw new InvalidParameterValueException("Filter " + TemplateFilter.all - + " can be specified by admin only"); - } - listAll = true; - } - - List permittedDomains = new ArrayList(); - List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary( - cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, cmd.listAll(), false, "listIsos"); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); -// List permittedAccounts = new ArrayList(); -// for (Long accountId : permittedAccountIds) { -// permittedAccounts.add(_accountMgr.getAccount(accountId)); -// } - - HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); - - return searchForTemplatesInternalIAM(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, - cmd.isBootable(), cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true, - cmd.listInReadyState(), permittedDomains, permittedAccounts, permittedResources, isRecursive, caller, listProjectResourcesCriteria, tags, showRemovedISO); - } @Override public ListResponse listAffinityGroups(Long affinityGroupId, String affinityGroupName, @@ -3576,14 +3180,14 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { throw new InvalidParameterValueException("Unable to list affinity groups for virtual machine instance " + vmId + "; instance not found."); } - _accountMgr.checkAccess(caller, null, userVM); + _accountMgr.checkAccess(caller, null, true, userVM); return listAffinityGroupsByVM(vmId.longValue(), startIndex, pageSize); } List permittedAccounts = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary( domainId, isRecursive, null); - buildTemplateAffinityGroupSearchParameters(caller, affinityGroupId, accountName, null, permittedAccounts, + _accountMgr.buildACLSearchParameters(caller, affinityGroupId, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, true); domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); @@ -3717,121 +3321,6 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { return sc; } - public Pair, Integer> listAffinityGroupsInternalIAM(Long affinityGroupId, - String affinityGroupName, String affinityGroupType, Long vmId, String accountName, Long domainId, - boolean isRecursive, boolean listAll, Long startIndex, Long pageSize, String keyword) { - - Account caller = CallContext.current().getCallingAccount(); - - caller.getAccountId(); - - if (vmId != null) { - UserVmVO userVM = _userVmDao.findById(vmId); - if (userVM == null) { - throw new InvalidParameterValueException("Unable to list affinity groups for virtual machine instance " + vmId + "; instance not found."); - } - _accountMgr.checkAccess(caller, null, userVM); - return listAffinityGroupsByVM(vmId.longValue(), startIndex, pageSize); - } - - List permittedDomains = new ArrayList(); - List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); - Ternary domainIdRecursiveListProject = new Ternary( - domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, affinityGroupId, accountName, null, permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, listAll, true, "listAffinityGroups"); - //domainId = domainIdRecursiveListProject.first(); - isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(AffinityGroupJoinVO.class, "id", true, startIndex, pageSize); - SearchCriteria sc = buildAffinityGroupSearchCriteriaIAM(isRecursive, - permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria, affinityGroupId, affinityGroupName, affinityGroupType, keyword); - - Pair, Integer> uniqueGroupsPair = _affinityGroupJoinDao.searchAndCount(sc, searchFilter); - // search group details by ids - List vrs = new ArrayList(); - Integer count = uniqueGroupsPair.second(); - if (count.intValue() != 0) { - List uniqueGroups = uniqueGroupsPair.first(); - Long[] vrIds = new Long[uniqueGroups.size()]; - int i = 0; - for (AffinityGroupJoinVO v : uniqueGroups) { - vrIds[i++] = v.getId(); - } - vrs = _affinityGroupJoinDao.searchByIds(vrIds); - } - - /* TODO: confirm with Prachi if we still need this complicated logic with new ACL model - if (!permittedAccounts.isEmpty()) { - // add domain level affinity groups - if (domainId != null) { - SearchCriteria scDomain = buildAffinityGroupSearchCriteria(null, isRecursive, - new ArrayList(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName, - affinityGroupType, keyword); - vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId)); - } else { - - for (Long permAcctId : permittedAccounts) { - Account permittedAcct = _accountDao.findById(permAcctId); - SearchCriteria scDomain = buildAffinityGroupSearchCriteria( - null, isRecursive, new ArrayList(), - listProjectResourcesCriteria, affinityGroupId, affinityGroupName, affinityGroupType, keyword); - - vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, permittedAcct.getDomainId())); - } - } - } else if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { - // list all domain level affinity groups for the domain admin case - SearchCriteria scDomain = buildAffinityGroupSearchCriteria(null, isRecursive, - new ArrayList(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName, - affinityGroupType, keyword); - vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId)); - } - */ - - return new Pair, Integer>(vrs, vrs.size()); - - } - - private SearchCriteria buildAffinityGroupSearchCriteriaIAM(boolean isRecursive, - List permittedDomains, List permittedAccounts, List permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria, - Long affinityGroupId, String affinityGroupName, String affinityGroupType, String keyword) { - - SearchBuilder groupSearch = _affinityGroupJoinDao.createSearchBuilder(); - groupSearch.select(null, Func.DISTINCT, groupSearch.entity().getId()); // select - // distinct - - SearchCriteria sc = groupSearch.create(); - SearchCriteria aclSc = _affinityGroupJoinDao.createSearchCriteria(); - // building ACL search criteria - _accountMgr.buildACLViewSearchCriteria(sc, aclSc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); - - if (affinityGroupId != null) { - sc.addAnd("id", SearchCriteria.Op.EQ, affinityGroupId); - } - - if (affinityGroupName != null) { - sc.addAnd("name", SearchCriteria.Op.EQ, affinityGroupName); - } - - if (affinityGroupType != null) { - sc.addAnd("type", SearchCriteria.Op.EQ, affinityGroupType); - } - - if (keyword != null) { - SearchCriteria ssc = _affinityGroupJoinDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - return sc; - - } - private Pair, Integer> listAffinityGroupsByVM(long vmId, long pageInd, long pageSize) { Filter sf = new Filter(SecurityGroupVMMapVO.class, null, true, pageInd, pageSize); Pair, Integer> agVmMappingPair = _affinityGroupVMMapDao.listByInstanceId(vmId, sf); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 9081051296c..14e29cb9f7e 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -175,8 +175,8 @@ import com.cloud.service.ServiceOfferingDetailsVO; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.service.dao.ServiceOfferingDetailsDao; -import com.cloud.storage.Storage.ProvisioningType; import com.cloud.storage.DiskOfferingVO; +import com.cloud.storage.Storage.ProvisioningType; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.test.IPRangeConfig; import com.cloud.user.Account; @@ -4339,7 +4339,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati throw new InvalidParameterValueException("Can't update system networks"); } - _accountMgr.checkAccess(caller, null, network); + _accountMgr.checkAccess(caller, null, true, network); List offeringIds = _networkModel.listNetworkOfferingsForUpgrade(networkId); diff --git a/server/src/com/cloud/network/IpAddressManagerImpl.java b/server/src/com/cloud/network/IpAddressManagerImpl.java index dc3a7addc91..4ecb354c9d0 100644 --- a/server/src/com/cloud/network/IpAddressManagerImpl.java +++ b/server/src/com/cloud/network/IpAddressManagerImpl.java @@ -29,8 +29,6 @@ import java.util.UUID; import javax.inject.Inject; -import org.apache.log4j.Logger; - import org.apache.cloudstack.acl.ControlledEntity.ACLType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.context.CallContext; @@ -42,6 +40,7 @@ import org.apache.cloudstack.region.PortableIp; import org.apache.cloudstack.region.PortableIpDao; import org.apache.cloudstack.region.PortableIpVO; import org.apache.cloudstack.region.Region; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.alert.AlertManager; @@ -410,7 +409,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage Account caller = CallContext.current().getCallingAccount(); long callerUserId = CallContext.current().getCallingUserId(); // check permissions - _accountMgr.checkAccess(caller, null, ipOwner); + _accountMgr.checkAccess(caller, null, false, ipOwner); DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId); @@ -1165,14 +1164,15 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage if (zone.getNetworkType() == NetworkType.Advanced) { if (network.getGuestType() == Network.GuestType.Shared) { if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) { - _accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.UseEntry, network); + _accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.UseEntry, false, + network); } else { throw new InvalidParameterValueException("IP can be associated with guest network of 'shared' type only if " + "network services Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network"); } } } else { - _accountMgr.checkAccess(caller, null, ipToAssoc); + _accountMgr.checkAccess(caller, null, true, ipToAssoc); } owner = _accountMgr.getAccount(ipToAssoc.getAllocatedToAccountId()); } else { @@ -1187,7 +1187,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage Network network = _networksDao.findById(networkId); if (network != null) { - _accountMgr.checkAccess(owner, AccessType.UseEntry, network); + _accountMgr.checkAccess(owner, AccessType.UseEntry, false, network); } else { s_logger.debug("Unable to find ip address by id: " + ipId); return null; @@ -1319,10 +1319,11 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage if (zone.getNetworkType() == NetworkType.Advanced) { if (network.getGuestType() == Network.GuestType.Shared) { assert (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())); - _accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.UseEntry, network); + _accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.UseEntry, false, + network); } } else { - _accountMgr.checkAccess(caller, null, ipToAssoc); + _accountMgr.checkAccess(caller, null, true, ipToAssoc); } owner = _accountMgr.getAccount(ipToAssoc.getAllocatedToAccountId()); } else { diff --git a/server/src/com/cloud/network/NetworkModelImpl.java b/server/src/com/cloud/network/NetworkModelImpl.java index 3aa797b0fcb..0ef5cb9984d 100755 --- a/server/src/com/cloud/network/NetworkModelImpl.java +++ b/server/src/com/cloud/network/NetworkModelImpl.java @@ -35,7 +35,6 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.apache.cloudstack.acl.ControlledEntity.ACLType; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao; @@ -1595,27 +1594,6 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { } } - @Override - public void checkNetworkPermissions(Account owner, Network network, AccessType accessType) { - if (network == null) { - throw new CloudRuntimeException("cannot check permissions on (Network) "); - } - - AccountVO networkOwner = _accountDao.findById(network.getAccountId()); - if (networkOwner == null) { - throw new PermissionDeniedException("Unable to use network with id= " + ((NetworkVO) network).getUuid() - + ", network does not have an owner"); - } - if (owner.getType() != Account.ACCOUNT_TYPE_PROJECT && networkOwner.getType() == Account.ACCOUNT_TYPE_PROJECT) { - if (!_projectAccountDao.canAccessProjectAccount(owner.getAccountId(), network.getAccountId())) { - throw new PermissionDeniedException("Unable to use network with id= " + ((NetworkVO) network).getUuid() - + ", permission denied"); - } - } else { - _accountMgr.checkAccess(owner, accessType, network); - } - } - @Override public String getDefaultPublicTrafficLabel(long dcId, HypervisorType hypervisorType) { try { diff --git a/server/src/com/cloud/network/NetworkServiceImpl.java b/server/src/com/cloud/network/NetworkServiceImpl.java index f1e5b2ad05d..00748951ee7 100755 --- a/server/src/com/cloud/network/NetworkServiceImpl.java +++ b/server/src/com/cloud/network/NetworkServiceImpl.java @@ -542,7 +542,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // if shared network in the advanced zone, then check the caller against the network for 'AccessType.UseNetwork' if (zone.getNetworkType() == NetworkType.Advanced) { if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) { - _accountMgr.checkAccess(caller, AccessType.UseEntry, network); + _accountMgr.checkAccess(caller, AccessType.UseEntry, false, network); if (s_logger.isDebugEnabled()) { s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId()); } @@ -554,7 +554,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } } else { - _accountMgr.checkAccess(caller, null, ipOwner); + _accountMgr.checkAccess(caller, null, false, ipOwner); } return _ipAddrMgr.allocateIp(ipOwner, false, caller, callerUserId, zone, displayIp); @@ -585,7 +585,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // if shared network in the advanced zone, then check the caller against the network for 'AccessType.UseNetwork' if (zone.getNetworkType() == NetworkType.Advanced) { if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) { - _accountMgr.checkAccess(caller, AccessType.UseEntry, network); + _accountMgr.checkAccess(caller, AccessType.UseEntry, false, network); if (s_logger.isDebugEnabled()) { s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId()); } @@ -605,7 +605,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } - _accountMgr.checkAccess(caller, null, ipOwner); + _accountMgr.checkAccess(caller, null, false, ipOwner); return _ipAddrMgr.allocatePortableIp(ipOwner, caller, zoneId, null, null); } @@ -671,7 +671,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { final Account ipOwner = _accountMgr.getAccount(vm.getAccountId()); // verify permissions - _accountMgr.checkAccess(caller, null, vm); + _accountMgr.checkAccess(caller, null, true, vm); Network network = _networksDao.findById(networkId); if (network == null) { @@ -767,7 +767,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterValueException("There is no vm with the given secondary ip"); } // verify permissions - _accountMgr.checkAccess(caller, null, vm); + _accountMgr.checkAccess(caller, null, true, vm); Network network = _networksDao.findById(secIpVO.getNetworkId()); @@ -891,7 +891,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // verify permissions if (ipVO.getAllocatedToAccountId() != null) { - _accountMgr.checkAccess(caller, null, ipVO); + _accountMgr.checkAccess(caller, null, true, ipVO); } if (ipVO.isSourceNat()) { @@ -1432,7 +1432,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain"); } - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, true, owner); permittedAccounts.add(owner.getId()); } } @@ -1816,7 +1816,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { Account owner = _accountMgr.getAccount(network.getAccountId()); // Perform permission check - _accountMgr.checkAccess(caller, null, network); + _accountMgr.checkAccess(caller, null, true, network); if (forced && !_accountMgr.isRootAdmin(caller.getId())) { throw new InvalidParameterValueException("Delete network with 'forced' option can only be called by root admins"); @@ -1860,7 +1860,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterException("Unable to restart a running SDN network."); } - _accountMgr.checkAccess(callerAccount, null, network); + _accountMgr.checkAccess(callerAccount, null, true, network); boolean success = _networkMgr.restartNetwork(networkId, callerAccount, callerUser, cleanup); @@ -1996,7 +1996,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest); } - _accountMgr.checkAccess(callerAccount, null, network); + _accountMgr.checkAccess(callerAccount, null, true, network); if (name != null) { network.setName(name); @@ -4045,7 +4045,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw ex; } - _accountMgr.checkAccess(caller, null, userVm); + _accountMgr.checkAccess(caller, null, true, userVm); return _networkMgr.listVmNics(vmId, nicId, networkId); } @@ -4069,7 +4069,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // verify permissions if (ipVO.getAllocatedToAccountId() != null) { - _accountMgr.checkAccess(caller, null, ipVO); + _accountMgr.checkAccess(caller, null, true, ipVO); } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { throw new PermissionDeniedException("Only Root admin can update non-allocated ip addresses"); } diff --git a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java index 09c66947016..d4de4625116 100644 --- a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java +++ b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java @@ -116,9 +116,9 @@ import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.TransactionCallback; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallback; import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.net.NetUtils; import com.cloud.vm.UserVmManager; @@ -240,7 +240,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale throw new InvalidParameterValueException("Unable to find " + paramName); } - _accountMgr.checkAccess(caller, null, (ControlledEntity)vo); + _accountMgr.checkAccess(caller, null, false, (ControlledEntity)vo); return vo; } @@ -342,7 +342,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale Account owner = _accountDao.findById(cmd.getAccountId()); Account caller = CallContext.current().getCallingAccount(); - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, true, owner); long zoneId = cmd.getZoneId(); long serviceOfferingId = cmd.getServiceOfferingId(); @@ -461,8 +461,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale Long zoneId = cmd.getZoneId(); Boolean display = cmd.getDisplay(); - SearchWrapper searchWrapper = new SearchWrapper(_autoScaleVmProfileDao, AutoScaleVmProfileVO.class, cmd, cmd.getId(), - "listAutoScaleVmProfiles"); + SearchWrapper searchWrapper = new SearchWrapper(_autoScaleVmProfileDao, AutoScaleVmProfileVO.class, cmd, cmd.getId()); SearchBuilder sb = searchWrapper.getSearchBuilder(); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); @@ -527,7 +526,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale ControlledEntity[] sameOwnerEntities = conditions.toArray(new ControlledEntity[conditions.size() + 1]); sameOwnerEntities[sameOwnerEntities.length - 1] = autoScalePolicyVO; - _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, sameOwnerEntities); + _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, sameOwnerEntities); if (conditionIds.size() != conditions.size()) { // TODO report the condition id which could not be found @@ -621,7 +620,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale idList.add(ApiDBUtils.findDomainById(domainId).getUuid()); throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specifed domainId"); } - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, false, owner); } private class SearchWrapper { @@ -630,14 +629,11 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale SearchCriteria searchCriteria; Long domainId; boolean isRecursive; - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); - ListProjectResourcesCriteria listProjectResourcesCriteria; Filter searchFilter; - public SearchWrapper(GenericDao dao, Class entityClass, BaseListAccountResourcesCmd cmd, Long id, String action) + public SearchWrapper(GenericDao dao, Class entityClass, BaseListAccountResourcesCmd cmd, Long id) { this.dao = dao; this.searchBuilder = dao.createSearchBuilder(); @@ -651,12 +647,12 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, listAll, - false, action); - //domainId = domainIdRecursiveListProject.first(); + _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, + listAll, false); + domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - _accountMgr.buildACLSearchBuilder(searchBuilder, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(searchBuilder, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); searchFilter = new Filter(entityClass, "id", false, startIndex, pageSizeVal); } @@ -666,7 +662,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale public SearchCriteria buildSearchCriteria() { searchCriteria = searchBuilder.create(); - _accountMgr.buildACLSearchCriteria(searchCriteria, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(searchCriteria, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); return searchCriteria; } @@ -677,8 +673,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale @Override public List listAutoScalePolicies(ListAutoScalePoliciesCmd cmd) { - SearchWrapper searchWrapper = new SearchWrapper(_autoScalePolicyDao, AutoScalePolicyVO.class, cmd, cmd.getId(), - "listAutoScalePolicies"); + SearchWrapper searchWrapper = new SearchWrapper(_autoScalePolicyDao, AutoScalePolicyVO.class, cmd, cmd.getId()); SearchBuilder sb = searchWrapper.getSearchBuilder(); Long id = cmd.getId(); Long conditionId = cmd.getConditionId(); @@ -884,8 +879,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale Long zoneId = cmd.getZoneId(); Boolean forDisplay = cmd.getDisplay(); - SearchWrapper searchWrapper = new SearchWrapper(_autoScaleVmGroupDao, AutoScaleVmGroupVO.class, cmd, cmd.getId(), - "listAutoScaleVmGroups"); + SearchWrapper searchWrapper = new SearchWrapper(_autoScaleVmGroupDao, AutoScaleVmGroupVO.class, cmd, cmd.getId()); SearchBuilder sb = searchWrapper.getSearchBuilder(); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); @@ -980,7 +974,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale ControlledEntity[] sameOwnerEntities = policies.toArray(new ControlledEntity[policies.size() + 2]); sameOwnerEntities[sameOwnerEntities.length - 2] = loadBalancer; sameOwnerEntities[sameOwnerEntities.length - 1] = profileVO; - _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, sameOwnerEntities); + _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, sameOwnerEntities); return Transaction.execute(new TransactionCallback() { @Override @@ -1176,7 +1170,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale Long id = cmd.getId(); Long counterId = cmd.getCounterId(); Long policyId = cmd.getPolicyId(); - SearchWrapper searchWrapper = new SearchWrapper(_conditionDao, ConditionVO.class, cmd, cmd.getId(), "listConditions"); + SearchWrapper searchWrapper = new SearchWrapper(_conditionDao, ConditionVO.class, cmd, cmd.getId()); SearchBuilder sb = searchWrapper.getSearchBuilder(); if (policyId != null) { SearchBuilder asPolicyConditionSearch = _autoScalePolicyConditionMapDao.createSearchBuilder(); diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java index 730606816b7..4f853b332a6 100644 --- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java +++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java @@ -263,26 +263,25 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService, Boolean display = cmd.getDisplay(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); if (ipId != null) { IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId); if (ipAddressVO == null || !ipAddressVO.readyToUse()) { throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for firewall rules yet"); } - _accountMgr.checkAccess(caller, null, ipAddressVO); + _accountMgr.checkAccess(caller, null, true, ipAddressVO); } Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, cmd.listAll(), false, "listFirewallRules"); + _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 filter = new Filter(FirewallRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _firewallDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), Op.EQ); sb.and("trafficType", sb.entity().getTrafficType(), Op.EQ); @@ -304,7 +303,7 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService, } SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (id != null) { sc.setParameters("id", id); @@ -464,7 +463,7 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService, } // Validate ip address - _accountMgr.checkAccess(caller, null, ipAddress); + _accountMgr.checkAccess(caller, null, true, ipAddress); } //network id either has to be passed explicitly, or implicitly as a part of ipAddress object @@ -476,7 +475,7 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService, assert network != null : "Can't create rule as network associated with public ip address is null?"; if (trafficType == FirewallRule.TrafficType.Egress) { - _accountMgr.checkAccess(caller, null, network); + _accountMgr.checkAccess(caller, null, true, network); } // Verify that the network guru supports the protocol specified @@ -639,7 +638,7 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService, } if (caller != null) { - _accountMgr.checkAccess(caller, null, rules.toArray(new FirewallRuleVO[rules.size()])); + _accountMgr.checkAccess(caller, null, true, rules.toArray(new FirewallRuleVO[rules.size()])); } try { @@ -693,7 +692,7 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService, throw new InvalidParameterValueException("Only root admin can delete the system wide firewall rule"); } - _accountMgr.checkAccess(caller, null, rule); + _accountMgr.checkAccess(caller, null, true, rule); revokeRule(rule, caller, userId, false); @@ -743,7 +742,7 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService, throw new InvalidParameterValueException("Only root admin can update the system wide firewall rule"); } - _accountMgr.checkAccess(caller, null, rule); + _accountMgr.checkAccess(caller, null, true, rule); if (customId != null) { rule.setUuid(customId); @@ -762,7 +761,7 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService, @DB public void revokeRule(final FirewallRuleVO rule, Account caller, long userId, final boolean needUsageEvent) { if (caller != null) { - _accountMgr.checkAccess(caller, null, rule); + _accountMgr.checkAccess(caller, null, true, rule); } Transaction.execute(new TransactionCallbackNoReturn() { diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index bc3ee767720..919c51273e8 100755 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -30,6 +30,11 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; +import org.apache.log4j.Logger; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBHealthCheckPolicyCmd; import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBStickinessPolicyCmd; @@ -45,7 +50,6 @@ import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationSe import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.lb.ApplicationLoadBalancerRuleVO; import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao; -import org.apache.log4j.Logger; import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.configuration.ConfigurationManager; @@ -165,8 +169,6 @@ import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.NicSecondaryIpDao; import com.cloud.vm.dao.UserVmDao; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; @Local(value = {LoadBalancingRulesManager.class, LoadBalancingRulesService.class}) public class LoadBalancingRulesManagerImpl extends ManagerBase implements LoadBalancingRulesManager, LoadBalancingRulesService { @@ -527,7 +529,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements throw new InvalidParameterValueException("Failed: LB rule id: " + cmd.getLbRuleId() + " not present "); } - _accountMgr.checkAccess(caller.getCallingAccount(), null, loadBalancer); + _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer); if (loadBalancer.getState() == FirewallRule.State.Revoke) { throw new InvalidParameterValueException("Failed: LB rule id: " + cmd.getLbRuleId() + " is in deleting state: "); } @@ -586,7 +588,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements throw new InvalidParameterValueException("Failed: LB rule id: " + cmd.getLbRuleId() + " not present "); } - _accountMgr.checkAccess(caller.getCallingAccount(), null, loadBalancer); + _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer); if (loadBalancer.getState() == FirewallRule.State.Revoke) { throw new InvalidParameterValueException("Failed: LB rule id: " + cmd.getLbRuleId() + " is in deleting state: "); @@ -748,7 +750,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements } long loadBalancerId = loadBalancer.getId(); FirewallRule.State backupState = loadBalancer.getState(); - _accountMgr.checkAccess(caller.getCallingAccount(), null, loadBalancer); + _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer); if (apply) { if (loadBalancer.getState() == FirewallRule.State.Active) { @@ -801,7 +803,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements } final long loadBalancerId = loadBalancer.getId(); FirewallRule.State backupState = loadBalancer.getState(); - _accountMgr.checkAccess(caller.getCallingAccount(), null, loadBalancer); + _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer); if (apply) { if (loadBalancer.getState() == FirewallRule.State.Active) { @@ -1193,7 +1195,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements throw new InvalidParameterException("Invalid certificate id: " + certId); } - _accountMgr.checkAccess(caller.getCallingAccount(), null, loadBalancer); + _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer); // check if LB and Cert belong to the same account if (loadBalancer.getAccountId() != certVO.getAccountId()) { @@ -1256,7 +1258,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements throw new InvalidParameterException("No certificate is bound to lb with id: " + lbRuleId); } - _accountMgr.checkAccess(caller.getCallingAccount(), null, loadBalancer); + _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer); boolean success = false; FirewallRule.State backupState = loadBalancer.getState(); @@ -1300,7 +1302,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements throw new InvalidParameterException("Invalid load balancer value: " + loadBalancerId); } - _accountMgr.checkAccess(caller.getCallingAccount(), null, loadBalancer); + _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer); if (instanceIds == null && vmIdIpMap.isEmpty()) { throw new InvalidParameterValueException("Both instanceids and vmidipmap can't be null"); @@ -1462,7 +1464,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements if (rule == null) { throw new InvalidParameterValueException("Unable to find load balancer rule " + loadBalancerId); } - _accountMgr.checkAccess(caller, null, rule); + _accountMgr.checkAccess(caller, null, true, rule); boolean result = deleteLoadBalancerRule(loadBalancerId, apply, caller, ctx.getCallingUserId(), true); if (!result) { @@ -1686,7 +1688,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements throw ex; } - _accountMgr.checkAccess(caller.getCallingAccount(), null, ipAddr); + _accountMgr.checkAccess(caller.getCallingAccount(), null, true, ipAddr); final Long networkId = ipAddr.getAssociatedWithNetworkId(); if (networkId == null) { @@ -2062,7 +2064,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements } // check permissions - _accountMgr.checkAccess(caller, null, lb); + _accountMgr.checkAccess(caller, null, true, lb); if (name != null) { lb.setName(name); @@ -2141,7 +2143,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements return null; } - _accountMgr.checkAccess(caller, null, loadBalancer); + _accountMgr.checkAccess(caller, null, true, loadBalancer); List loadBalancerInstances = new ArrayList(); List serviceStates = new ArrayList(); @@ -2220,7 +2222,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements return null; } - _accountMgr.checkAccess(caller, null, loadBalancer); + _accountMgr.checkAccess(caller, null, true, loadBalancer); List sDbpolicies = _lb2stickinesspoliciesDao.listByLoadBalancerIdAndDisplayFlag(cmd.getLbRuleId(), forDisplay); @@ -2237,8 +2239,10 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements if (loadBalancer == null) { return null; } - _accountMgr.checkAccess(caller, null, loadBalancer); + + _accountMgr.checkAccess(caller, null, true, loadBalancer); List hcDbpolicies = _lb2healthcheckDao.listByLoadBalancerIdAndDisplayFlag(cmd.getLbRuleId(), forDisplay); + return hcDbpolicies; } @@ -2255,21 +2259,19 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements Boolean forDisplay = cmd.getDisplay(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary( cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, cmd.listAll(), false, "listLoadBalancerRules"); - //Long domainId = domainIdRecursiveListProject.first(); + _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(LoadBalancerVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _lbDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); @@ -2303,7 +2305,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements } SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (keyword != null) { SearchCriteria ssc = _lbDao.createSearchCriteria(); @@ -2486,7 +2488,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements throw new InvalidParameterException("Invalid Load balancer : " + policy.getLoadBalancerId() + " for Stickiness policy id: " + id); } - _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, loadBalancer); + _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, loadBalancer); if (customId != null) { policy.setUuid(customId); @@ -2513,7 +2515,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements throw new InvalidParameterException("Invalid Load balancer : " + policy.getLoadBalancerId() + " for Stickiness policy id: " + id); } - _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, loadBalancer); + _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, loadBalancer); if (customId != null) { policy.setUuid(customId); diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 2e7b5a11cfd..98db77837bc 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -463,7 +463,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V return null; } - _accountMgr.checkAccess(caller, null, router); + _accountMgr.checkAccess(caller, null, true, router); _itMgr.expunge(router.getUuid()); _routerDao.remove(router.getId()); @@ -482,7 +482,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V throw new InvalidParameterValueException("Unable to find router with id " + routerId); } - _accountMgr.checkAccess(caller, null, router); + _accountMgr.checkAccess(caller, null, true, router); if (router.getServiceOfferingId() == serviceOfferingId) { s_logger.debug("Router: " + routerId + "already has service offering: " + serviceOfferingId); @@ -597,7 +597,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V throw new InvalidParameterValueException("Unable to find router by id " + routerId + "."); } - _accountMgr.checkAccess(account, null, router); + _accountMgr.checkAccess(account, null, true, router); final UserVO user = _userDao.findById(CallContext.current().getCallingUserId()); @@ -656,7 +656,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V throw new InvalidParameterValueException("Unable to find domain router with id " + routerId + "."); } - _accountMgr.checkAccess(caller, null, router); + _accountMgr.checkAccess(caller, null, true, router); // Can reboot domain router only in Running state if (router == null || router.getState() != State.Running) { @@ -3300,7 +3300,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V if (router == null) { throw new InvalidParameterValueException("Unable to find router by id " + routerId + "."); } - _accountMgr.checkAccess(caller, null, router); + _accountMgr.checkAccess(caller, null, true, router); final Account owner = _accountMgr.getAccount(router.getAccountId()); diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index a0d6cd6510b..eea12625d70 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -27,7 +27,6 @@ import javax.inject.Inject; import org.apache.log4j.Logger; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.command.user.firewall.ListPortForwardingRulesCmd; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; @@ -164,7 +163,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules } } - _accountMgr.checkAccess(caller, AccessType.OperateEntry, ipAddress, userVm); + _accountMgr.checkAccess(caller, null, true, ipAddress, userVm); // validate that IP address and userVM belong to the same account if (ipAddress.getAllocatedToAccountId().longValue() != userVm.getAccountId()) { @@ -189,7 +188,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules return; } - _accountMgr.checkAccess(caller, AccessType.OperateEntry, rule, userVm); + _accountMgr.checkAccess(caller, null, true, rule, userVm); if (userVm.getState() == VirtualMachine.State.Destroyed || userVm.getState() == VirtualMachine.State.Expunging) { throw new InvalidParameterValueException("Invalid user vm: " + userVm.getId()); @@ -683,7 +682,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules throw new InvalidParameterValueException("Unable to find " + ruleId); } - _accountMgr.checkAccess(caller, null, rule); + _accountMgr.checkAccess(caller, null, true, rule); if (!revokePortForwardingRuleInternal(ruleId, caller, ctx.getCallingUserId(), apply)) { throw new CloudRuntimeException("Failed to delete port forwarding rule"); @@ -718,7 +717,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules throw new InvalidParameterValueException("Unable to find " + ruleId); } - _accountMgr.checkAccess(caller, null, rule); + _accountMgr.checkAccess(caller, null, true, rule); if (!revokeStaticNatRuleInternal(ruleId, caller, ctx.getCallingUserId(), apply)) { throw new CloudRuntimeException("Failed to revoke forwarding rule"); @@ -785,27 +784,25 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules Boolean display = cmd.getDisplay(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); if (ipId != null) { IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId); if (ipAddressVO == null || !ipAddressVO.readyToUse()) { throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for port forwarding rules yet"); } - _accountMgr.checkAccess(caller, null, ipAddressVO); + _accountMgr.checkAccess(caller, null, true, ipAddressVO); } Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, cmd.listAll(), false, "listPortForwardingRules"); + _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 filter = new Filter(PortForwardingRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _portForwardingDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), Op.EQ); sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ); @@ -826,7 +823,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules } SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (id != null) { sc.setParameters("id", id); @@ -869,7 +866,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules } if (caller != null) { - _accountMgr.checkAccess(caller, null, rules.toArray(new PortForwardingRuleVO[rules.size()])); + _accountMgr.checkAccess(caller, null, true, rules.toArray(new PortForwardingRuleVO[rules.size()])); } try { @@ -898,7 +895,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules } if (caller != null) { - _accountMgr.checkAccess(caller, null, staticNatRules.toArray(new StaticNatRule[staticNatRules.size()])); + _accountMgr.checkAccess(caller, null, true, staticNatRules.toArray(new StaticNatRule[staticNatRules.size()])); } try { @@ -922,7 +919,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules } if (caller != null) { - _accountMgr.checkAccess(caller, null, rules.toArray(new PortForwardingRuleVO[rules.size()])); + _accountMgr.checkAccess(caller, null, true, rules.toArray(new PortForwardingRuleVO[rules.size()])); } try { @@ -948,7 +945,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules } if (caller != null) { - _accountMgr.checkAccess(caller, null, rules.toArray(new FirewallRule[rules.size()])); + _accountMgr.checkAccess(caller, null, true, rules.toArray(new FirewallRule[rules.size()])); } for (FirewallRuleVO rule : rules) { @@ -976,7 +973,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules } if (caller != null) { - _accountMgr.checkAccess(caller, null, ips.toArray(new IPAddressVO[ips.size()])); + _accountMgr.checkAccess(caller, null, true, ips.toArray(new IPAddressVO[ips.size()])); } List staticNats = new ArrayList(); @@ -1003,27 +1000,25 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules public Pair, Integer> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll) { Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); if (ipId != null) { IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId); if (ipAddressVO == null || !ipAddressVO.readyToUse()) { throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for port forwarding rules yet"); } - _accountMgr.checkAccess(caller, null, ipAddressVO); + _accountMgr.checkAccess(caller, null, true, ipAddressVO); } Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, listAll, - false, "listIpForwardingRules"); + _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, false); + domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, start, size); SearchBuilder sb = _firewallDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ); sb.and("purpose", sb.entity().getPurpose(), Op.EQ); @@ -1036,7 +1031,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules } SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sc.setParameters("purpose", Purpose.StaticNat); if (id != null) { @@ -1388,7 +1383,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules } if (caller != null) { - _accountMgr.checkAccess(caller, null, sourceIp); + _accountMgr.checkAccess(caller, null, true, sourceIp); } // create new static nat rule @@ -1507,7 +1502,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules if (rule == null) { throw new InvalidParameterValueException("Unable to find " + id); } - _accountMgr.checkAccess(caller, null, rule); + _accountMgr.checkAccess(caller, null, true, rule); if (customId != null) { rule.setUuid(customId); diff --git a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java index b4c67b8d74d..f60a746e68c 100755 --- a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -612,7 +612,7 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro } // Verify permissions - _accountMgr.checkAccess(caller, null, securityGroup); + _accountMgr.checkAccess(caller, null, true, securityGroup); Long domainId = owner.getDomainId(); if (protocol == null) { @@ -819,7 +819,7 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro // Check permissions SecurityGroup securityGroup = _securityGroupDao.findById(rule.getSecurityGroupId()); - _accountMgr.checkAccess(caller, AccessType.OperateEntry, securityGroup); + _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, securityGroup); long securityGroupId = rule.getSecurityGroupId(); Boolean result = Transaction.execute(new TransactionCallback() { @@ -1120,7 +1120,7 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro } // check permissions - _accountMgr.checkAccess(caller, null, group); + _accountMgr.checkAccess(caller, null, true, group); return Transaction.execute(new TransactionCallbackWithException() { @Override @@ -1359,7 +1359,7 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro } // Verify permissions - _accountMgr.checkAccess(caller, null, vm); + _accountMgr.checkAccess(caller, null, false, vm); // Validate parameters List vmSgGrps = getSecurityGroupsForVm(vmId); diff --git a/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java b/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java index 72996d160cd..19a26c16277 100644 --- a/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java +++ b/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java @@ -103,7 +103,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ if (vpc == null) { throw new InvalidParameterValueException("Unable to find VPC"); } - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, true, vpc); return _networkAclMgr.createNetworkACL(name, description, vpcId, forDisplay); } @@ -161,7 +161,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ if (vpc == null) { throw new InvalidParameterValueException("Unable to find VPC"); } - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, true, vpc); //Include vpcId 0 to list default ACLs sc.setParameters("vpcId", vpcId, 0); } else { @@ -169,26 +169,23 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ // VpcId is not specified. Find permitted VPCs for the caller // and list ACLs belonging to the permitted VPCs - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); - Long domainId = cmd.getDomainId(); boolean isRecursive = cmd.isRecursive(); String accountName = cmd.getAccountName(); Long projectId = cmd.getProjectId(); boolean listAll = cmd.listAll(); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, - listAll, false, "listNetworkACLLists"); - //domainId = domainIdRecursiveListProject.first(); + ListProjectResourcesCriteria>(domainId, isRecursive, null); + _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, + listAll, false); + domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); SearchBuilder sbVpc = _vpcDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sbVpc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sbVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); SearchCriteria scVpc = sbVpc.create(); - _accountMgr.buildACLSearchCriteria(scVpc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(scVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); List vpcs = _vpcDao.search(scVpc, null); List vpcIds = new ArrayList(); for (VpcVO vpc : vpcs) { @@ -225,7 +222,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ if (vpc == null) { throw new InvalidParameterValueException("Unable to find specified VPC associated with the ACL"); } - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, true, vpc); return _networkAclMgr.deleteNetworkACL(acl); } @@ -256,14 +253,14 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ if (vpc == null) { throw new InvalidParameterValueException("Unable to find Vpc associated with the NetworkACL"); } - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, true, vpc); if (!gateway.getVpcId().equals(acl.getVpcId())) { throw new InvalidParameterValueException("private gateway: " + privateGatewayId + " and ACL: " + aclId + " do not belong to the same VPC"); } } PrivateGateway privateGateway = _vpcSvc.getVpcPrivateGateway(gateway.getId()); - _accountMgr.checkAccess(caller, null, privateGateway); + _accountMgr.checkAccess(caller, null, true, privateGateway); return _networkAclMgr.replaceNetworkACLForPrivateGw(acl, privateGateway); @@ -299,7 +296,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ throw new InvalidParameterValueException("Unable to find Vpc associated with the NetworkACL"); } - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, true, vpc); if (!network.getVpcId().equals(acl.getVpcId())) { throw new InvalidParameterValueException("Network: " + networkId + " and ACL: " + aclId + " do not belong to the same VPC"); } @@ -371,7 +368,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ if (vpc == null) { throw new InvalidParameterValueException("Unable to find Vpc associated with the NetworkACL"); } - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, true, vpc); //Ensure that number is unique within the ACL if (aclItemCmd.getNumber() != null) { @@ -488,7 +485,6 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ String action = cmd.getAction(); Map tags = cmd.getTags(); Account caller = CallContext.current().getCallingAccount(); - Boolean display = cmd.getDisplay(); Filter filter = new Filter(NetworkACLItemVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _networkACLItemDao.createSearchBuilder(); @@ -498,7 +494,6 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ sb.and("trafficType", sb.entity().getTrafficType(), Op.EQ); sb.and("protocol", sb.entity().getProtocol(), Op.EQ); sb.and("action", sb.entity().getAction(), Op.EQ); - sb.and("display", sb.entity().isDisplay(), Op.EQ); if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); @@ -521,10 +516,6 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ SearchCriteria sc = sb.create(); - if (display != null) { - sc.setParameters("display", display); - } - if (id != null) { sc.setParameters("id", id); } @@ -551,33 +542,32 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ if (vpc == null) { throw new InvalidParameterValueException("Unable to find VPC associated with acl"); } - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, true, vpc); } sc.setParameters("aclId", aclId); } else { //ToDo: Add accountId to network_acl_item table for permission check + // aclId is not specified // List permitted VPCs and filter aclItems - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Long domainId = cmd.getDomainId(); boolean isRecursive = cmd.isRecursive(); String accountName = cmd.getAccountName(); Long projectId = cmd.getProjectId(); boolean listAll = cmd.listAll(); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, - listAll, false, "listNetworkACLs"); + ListProjectResourcesCriteria>(domainId, isRecursive, null); + _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, + listAll, false); domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); SearchBuilder sbVpc = _vpcDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sbVpc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sbVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); SearchCriteria scVpc = sbVpc.create(); - _accountMgr.buildACLSearchCriteria(scVpc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(scVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); List vpcs = _vpcDao.search(scVpc, null); List vpcIds = new ArrayList(); for (VpcVO vpc : vpcs) { @@ -620,7 +610,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ Account caller = CallContext.current().getCallingAccount(); - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, true, vpc); if((aclItem.getAclId() == NetworkACL.DEFAULT_ALLOW) || (aclItem.getAclId() == NetworkACL.DEFAULT_DENY)){ throw new InvalidParameterValueException("ACL Items in default ACL cannot be deleted"); @@ -647,7 +637,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ Account caller = CallContext.current().getCallingAccount(); - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, true, vpc); if (number != null) { //Check if ACL Item with specified number already exists @@ -669,7 +659,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ NetworkACLVO acl = _networkACLDao.findById(id); Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId()); Account caller = CallContext.current().getCallingAccount(); - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, true, vpc); if (customId != null) { acl.setUuid(customId); diff --git a/server/src/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/com/cloud/network/vpc/VpcManagerImpl.java index aa3415c86eb..9d30fc7ab86 100644 --- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java +++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java @@ -35,8 +35,9 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.log4j.Logger; + import org.apache.cloudstack.acl.ControlledEntity.ACLType; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.command.user.vpc.ListPrivateGatewaysCmd; import org.apache.cloudstack.api.command.user.vpc.ListStaticRoutesCmd; import org.apache.cloudstack.context.CallContext; @@ -44,7 +45,6 @@ import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationSe import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.managed.context.ManagedContextRunnable; -import org.apache.log4j.Logger; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; @@ -760,7 +760,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis Account owner = _accountMgr.getAccount(vpcOwnerId); //Verify that caller can perform actions in behalf of vpc owner - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, false, owner); //check resource limit _resourceLimitMgr.checkResourceLimit(owner, ResourceType.vpc); @@ -893,7 +893,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis } //verify permissions - _accountMgr.checkAccess(ctx.getCallingAccount(), null, vpc); + _accountMgr.checkAccess(ctx.getCallingAccount(), null, false, vpc); return destroyVpc(vpc, ctx.getCallingAccount(), ctx.getCallingUserId()); } @@ -961,7 +961,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis throw new InvalidParameterValueException("Unable to find vpc by id " + vpcId); } - _accountMgr.checkAccess(caller, null, vpcToUpdate); + _accountMgr.checkAccess(caller, null, false, vpcToUpdate); VpcVO vpc = _vpcDao.createForUpdate(vpcId); @@ -994,20 +994,18 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis String accountName, Long domainId, String keyword, Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, Boolean restartRequired, Map tags, Long projectId, Boolean display) { Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); - Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, listAll, - false, "listVPCs"); + _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, + listAll, false); + domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(VpcVO.class, "created", false, startIndex, pageSizeVal); SearchBuilder sb = _vpcDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); @@ -1033,7 +1031,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis // now set the SC criteria... SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (keyword != null) { SearchCriteria ssc = _vpcDao.createSearchCriteria(); @@ -1153,7 +1151,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis } //permission check - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, false, vpc); DataCenter dc = _entityMgr.findById(DataCenter.class, vpc.getZoneId()); @@ -1213,7 +1211,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis } //permission check - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, false, vpc); //shutdown provider s_logger.debug("Shutting down vpc " + vpc); @@ -1479,7 +1477,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis throw ex; } - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, false, vpc); s_logger.debug("Restarting VPC " + vpc); boolean restartRequired = false; @@ -1796,23 +1794,21 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); String state = cmd.getState(); Long projectId = cmd.getProjectId(); Filter searchFilter = new Filter(VpcGatewayVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, listAll, - false, "listPrivateGateways"); + _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, + listAll, false); + domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); SearchBuilder sb = _vpcGatewayDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); - + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (vlan != null) { SearchBuilder ntwkSearch = _ntwkDao.createSearchBuilder(); ntwkSearch.and("vlan", ntwkSearch.entity().getBroadcastUri(), SearchCriteria.Op.EQ); @@ -1820,8 +1816,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis } SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); - + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (id != null) { sc.addAnd("id", Op.EQ, id); } @@ -1933,7 +1928,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis throw new InvalidParameterValueException("Unable to find static route by id"); } - _accountMgr.checkAccess(caller, null, route); + _accountMgr.checkAccess(caller, null, false, route); markStaticRouteForRevoke(route, caller); @@ -1981,7 +1976,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis if (vpc == null) { throw new InvalidParameterValueException("Can't add static route to VPC that is being deleted"); } - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, false, vpc); if (!NetUtils.isValidCIDR(cidr)) { throw new InvalidParameterValueException("Invalid format for cidr " + cidr); @@ -2049,23 +2044,21 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis Boolean listAll = cmd.listAll(); String accountName = cmd.getAccountName(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); - Map tags = cmd.getTags(); Long projectId = cmd.getProjectId(); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, listAll, - false, "listStaticRoutes"); + _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, + listAll, false); + domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(StaticRouteVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _staticRouteDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); @@ -2084,8 +2077,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis } SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); - + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (id != null) { sc.addAnd("id", Op.EQ, id); } @@ -2133,7 +2125,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis protected void markStaticRouteForRevoke(StaticRouteVO route, Account caller) { s_logger.debug("Revoking static route " + route); if (caller != null) { - _accountMgr.checkAccess(caller, null, route); + _accountMgr.checkAccess(caller, null, false, route); } if (route.getState() == StaticRoute.State.Staged) { @@ -2192,6 +2184,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis IpAddress ipToAssoc = _ntwkModel.getIp(ipId); if (ipToAssoc != null) { + _accountMgr.checkAccess(caller, null, true, ipToAssoc); owner = _accountMgr.getAccount(ipToAssoc.getAllocatedToAccountId()); } else { s_logger.debug("Unable to find ip address by id: " + ipId); @@ -2204,7 +2197,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis } // check permissions - _accountMgr.checkAccess(caller, AccessType.OperateEntry, ipToAssoc, vpc); + _accountMgr.checkAccess(caller, null, true, owner, vpc); boolean isSourceNat = false; if (getExistingSourceNatInVpc(owner.getId(), vpcId) == null) { @@ -2284,7 +2277,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis ex.addProxyObject(String.valueOf(vpcId), "VPC"); throw ex; } - _accountMgr.checkAccess(caller, null, vpc); + _accountMgr.checkAccess(caller, null, false, vpc); if (networkDomain == null) { networkDomain = vpc.getNetworkDomain(); diff --git a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java index 9d9118c0211..757f618eeb8 100755 --- a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java @@ -150,7 +150,7 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId); } - _accountMgr.checkAccess(caller, null, ipAddr); + _accountMgr.checkAccess(caller, null, true, ipAddr); if (!ipAddr.readyToUse()) { throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress()); @@ -292,7 +292,7 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc return true; } - _accountMgr.checkAccess(caller, AccessType.OperateEntry, vpn); + _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, vpn); RemoteAccessVpn.State prevState = vpn.getState(); vpn.setState(RemoteAccessVpn.State.Removed); @@ -395,7 +395,7 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc if (owner == null) { throw new InvalidParameterValueException("Unable to add vpn user: Another operation active"); } - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, true, owner); //don't allow duplicated user names for the same account VpnUserVO vpnUser = _vpnUsersDao.findByAccountAndUsername(owner.getId(), username); @@ -424,7 +424,7 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc if (user == null) { throw new InvalidParameterValueException("Could not find vpn user " + username); } - _accountMgr.checkAccess(caller, null, user); + _accountMgr.checkAccess(caller, null, true, user); Transaction.execute(new TransactionCallbackNoReturn() { @Override @@ -443,7 +443,7 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc public List listVpnUsers(long vpnOwnerId, String userName) { Account caller = CallContext.current().getCallingAccount(); Account owner = _accountDao.findById(vpnOwnerId); - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, true, owner); return _vpnUsersDao.listByAccount(vpnOwnerId); } @@ -461,7 +461,7 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc openFirewall = false; } - _accountMgr.checkAccess(caller, null, vpn); + _accountMgr.checkAccess(caller, null, true, vpn); boolean started = false; try { @@ -507,7 +507,7 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc public boolean applyVpnUsers(long vpnOwnerId, String userName) { Account caller = CallContext.current().getCallingAccount(); Account owner = _accountDao.findById(vpnOwnerId); - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, true, owner); s_logger.debug("Applying vpn users for " + owner); List vpns = _remoteAccessVpnDao.findByAccount(vpnOwnerId); @@ -586,26 +586,24 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc String username = cmd.getUsername(); Long id = cmd.getId(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, cmd.listAll(), false, "listVpnUsers"); - //Long domainId = domainIdRecursiveListProject.first(); + _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(VpnUserVO.class, "username", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _vpnUsersDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.EQ); sb.and("state", sb.entity().getState(), Op.IN); SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); //list only active users sc.setParameters("state", State.Active, State.Add); @@ -627,9 +625,7 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc // do some parameter validation Account caller = CallContext.current().getCallingAccount(); Long ipAddressId = cmd.getPublicIpId(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Long vpnId = cmd.getId(); Long networkId = cmd.getNetworkId(); @@ -644,19 +640,18 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId + " is not associated with an account."); } } - _accountMgr.checkAccess(caller, null, publicIp); + _accountMgr.checkAccess(caller, null, true, publicIp); } Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, cmd.listAll(), false, "listRemoteAccessVpns"); - //Long domainId = domainIdRecursiveListProject.first(); + _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(); Filter filter = new Filter(RemoteAccessVpnVO.class, "serverAddressId", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _remoteAccessVpnDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("serverAddressId", sb.entity().getServerAddressId(), Op.EQ); sb.and("id", sb.entity().getId(), Op.EQ); @@ -665,7 +660,8 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc sb.and("display", sb.entity().isDisplay(), Op.EQ); SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + sc.setParameters("state", RemoteAccessVpn.State.Running); @@ -755,7 +751,7 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc throw new InvalidParameterValueException("Can't find remote access vpn by id " + id); } - _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, vpn); + _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, vpn); if (customId != null) { vpn.setUuid(customId); } diff --git a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java index a34aa6c7e81..e6d0b1233f1 100644 --- a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java @@ -125,7 +125,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); //Verify that caller can perform actions in behalf of vpc owner - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, false, owner); Long vpcId = cmd.getVpcId(); VpcVO vpc = _vpcDao.findById(vpcId); @@ -175,7 +175,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); //Verify that caller can perform actions in behalf of vpc owner - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, false, owner); String name = cmd.getName(); String gatewayIp = cmd.getGatewayIp(); @@ -243,21 +243,21 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); //Verify that caller can perform actions in behalf of vpc owner - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, false, owner); Long customerGatewayId = cmd.getCustomerGatewayId(); Site2SiteCustomerGateway customerGateway = _customerGatewayDao.findById(customerGatewayId); if (customerGateway == null) { throw new InvalidParameterValueException("Unable to found specified Site to Site VPN customer gateway " + customerGatewayId + " !"); } - _accountMgr.checkAccess(caller, null, customerGateway); + _accountMgr.checkAccess(caller, null, false, customerGateway); Long vpnGatewayId = cmd.getVpnGatewayId(); Site2SiteVpnGateway vpnGateway = _vpnGatewayDao.findById(vpnGatewayId); if (vpnGateway == null) { throw new InvalidParameterValueException("Unable to found specified Site to Site VPN gateway " + vpnGatewayId + " !"); } - _accountMgr.checkAccess(caller, null, vpnGateway); + _accountMgr.checkAccess(caller, null, false, vpnGateway); if (customerGateway.getAccountId() != vpnGateway.getAccountId() || customerGateway.getDomainId() != vpnGateway.getDomainId()) { throw new InvalidParameterValueException("VPN connection can only be esitablished between same account's VPN gateway and customer gateway!"); @@ -363,7 +363,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn if (customerGateway == null) { throw new InvalidParameterValueException("Fail to find customer gateway with " + id + " !"); } - _accountMgr.checkAccess(caller, null, customerGateway); + _accountMgr.checkAccess(caller, null, false, customerGateway); return doDeleteCustomerGateway(customerGateway); } @@ -398,7 +398,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn throw new InvalidParameterValueException("Fail to find vpn gateway with " + id + " !"); } - _accountMgr.checkAccess(caller, null, vpnGateway); + _accountMgr.checkAccess(caller, null, false, vpnGateway); doDeleteVpnGateway(vpnGateway); return true; @@ -415,7 +415,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn if (gw == null) { throw new InvalidParameterValueException("Find to find customer gateway with id " + id); } - _accountMgr.checkAccess(caller, null, gw); + _accountMgr.checkAccess(caller, null, false, gw); List conns = _vpnConnectionDao.listByCustomerGatewayId(id); if (conns != null) { @@ -505,7 +505,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn throw new InvalidParameterValueException("Fail to find site to site VPN connection " + id + " to delete!"); } - _accountMgr.checkAccess(caller, null, conn); + _accountMgr.checkAccess(caller, null, false, conn); if (conn.getState() == State.Connected) { stopVpnConnection(id); @@ -554,7 +554,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn if (conn == null) { throw new InvalidParameterValueException("Fail to find site to site VPN connection " + id + " to reset!"); } - _accountMgr.checkAccess(caller, null, conn); + _accountMgr.checkAccess(caller, null, false, conn); if (conn.getState() == State.Pending) { throw new InvalidParameterValueException("VPN connection " + id + " cannot be reseted when state is Pending!"); @@ -578,26 +578,23 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn long pageSizeVal = cmd.getPageSizeVal(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, listAll, false, - "listVpnCustomerGateways"); - //domainId = domainIdRecursiveListProject.first(); + _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false); + domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(Site2SiteCustomerGatewayVO.class, "id", false, startIndex, pageSizeVal); SearchBuilder sb = _customerGatewayDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); @@ -621,28 +618,25 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn long pageSizeVal = cmd.getPageSizeVal(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, listAll, false, - "listVpnGateways"); - //domainId = domainIdRecursiveListProject.first(); + _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false); + domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(Site2SiteVpnGatewayVO.class, "id", false, startIndex, pageSizeVal); SearchBuilder sb = _vpnGatewayDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); sb.and("display", sb.entity().isDisplay(), SearchCriteria.Op.EQ); SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); @@ -674,21 +668,18 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn long pageSizeVal = cmd.getPageSizeVal(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, listAll, false, - "listVpnConnections"); - //domainId = domainIdRecursiveListProject.first(); + _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false); + domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(Site2SiteVpnConnectionVO.class, "id", false, startIndex, pageSizeVal); SearchBuilder sb = _vpnConnectionDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("display", sb.entity().isDisplay(), SearchCriteria.Op.EQ); @@ -700,7 +691,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn } SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (display != null) { sc.setParameters("display", display); @@ -818,7 +809,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn throw new InvalidParameterValueException("Fail to find site to site VPN connection " + id); } - _accountMgr.checkAccess(caller, null, conn); + _accountMgr.checkAccess(caller, null, false, conn); if (customId != null) { conn.setUuid(customId); } @@ -841,7 +832,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn throw new InvalidParameterValueException("Fail to find vpn gateway with " + id); } - _accountMgr.checkAccess(caller, null, vpnGateway); + _accountMgr.checkAccess(caller, null, false, vpnGateway); if (customId != null) { vpnGateway.setUuid(customId); } diff --git a/server/src/com/cloud/projects/ProjectManagerImpl.java b/server/src/com/cloud/projects/ProjectManagerImpl.java index 6aa5abc0e8c..d10c059bd52 100755 --- a/server/src/com/cloud/projects/ProjectManagerImpl.java +++ b/server/src/com/cloud/projects/ProjectManagerImpl.java @@ -244,7 +244,7 @@ public class ProjectManagerImpl extends ManagerBase implements ProjectManager { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } - _accountMgr.checkAccess(caller, AccessType.ModifyProject, _accountMgr.getAccount(project.getProjectAccountId())); + _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); //at this point enabling project doesn't require anything, so just update the state project.setState(State.Active); @@ -264,7 +264,7 @@ public class ProjectManagerImpl extends ManagerBase implements ProjectManager { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } - _accountMgr.checkAccess(ctx.getCallingAccount(), AccessType.ModifyProject, _accountMgr.getAccount(project.getProjectAccountId())); + _accountMgr.checkAccess(ctx.getCallingAccount(), AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); return deleteProject(ctx.getCallingAccount(), ctx.getCallingUserId(), project); } @@ -463,7 +463,7 @@ public class ProjectManagerImpl extends ManagerBase implements ProjectManager { } //verify permissions - _accountMgr.checkAccess(caller, AccessType.ModifyProject, _accountMgr.getAccount(project.getProjectAccountId())); + _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); Transaction.execute(new TransactionCallbackWithExceptionNoReturn() { @Override @@ -550,7 +550,7 @@ public class ProjectManagerImpl extends ManagerBase implements ProjectManager { } //verify permissions - only project owner can assign - _accountMgr.checkAccess(caller, AccessType.ModifyProject, _accountMgr.getAccount(project.getProjectAccountId())); + _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); //Check if the account already added to the project ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId()); @@ -628,7 +628,7 @@ public class ProjectManagerImpl extends ManagerBase implements ProjectManager { } //verify permissions - _accountMgr.checkAccess(caller, AccessType.ModifyProject, _accountMgr.getAccount(project.getProjectAccountId())); + _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); //Check if the account exists in the project ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId()); @@ -750,7 +750,7 @@ public class ProjectManagerImpl extends ManagerBase implements ProjectManager { } //verify permissions - _accountMgr.checkAccess(caller, null, account); + _accountMgr.checkAccess(caller, null, true, account); accountId = account.getId(); } else { @@ -830,7 +830,7 @@ public class ProjectManagerImpl extends ManagerBase implements ProjectManager { } //verify permissions - _accountMgr.checkAccess(caller, AccessType.ModifyProject, _accountMgr.getAccount(project.getProjectAccountId())); + _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); //allow project activation only when it's in Suspended state Project.State currentState = project.getState(); @@ -870,7 +870,7 @@ public class ProjectManagerImpl extends ManagerBase implements ProjectManager { throw ex; } - _accountMgr.checkAccess(caller, AccessType.ModifyProject, _accountMgr.getAccount(project.getProjectAccountId())); + _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); if (suspendProject(project)) { s_logger.debug("Successfully suspended project id=" + projectId); @@ -1012,7 +1012,7 @@ public class ProjectManagerImpl extends ManagerBase implements ProjectManager { Project project = getProject(invitation.getProjectId()); //check permissions - only project owner can remove the invitations - _accountMgr.checkAccess(caller, AccessType.ModifyProject, _accountMgr.getAccount(project.getProjectAccountId())); + _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); if (_projectInvitationDao.remove(id)) { s_logger.debug("Project Invitation id=" + id + " is removed"); diff --git a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java index 0c0c588d96f..b6977c2808a 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; diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 1342e7d507d..790441bdb91 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 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 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 sb = _publicIpAddressDao.createSearchBuilder(); Long domainId = null; Boolean isRecursive = null; - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); - ListProjectResourcesCriteria listProjectResourcesCriteria = null; if (isAllocated) { Account caller = CallContext.current().getCallingAccount(); Ternary domainIdRecursiveListProject = new Ternary( 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 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); @@ -3314,7 +3311,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) { @@ -3421,7 +3418,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); @@ -3580,22 +3577,21 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe String fingerPrint = cmd.getFingerprint(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary( 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 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 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); @@ -3660,7 +3656,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"); @@ -3833,7 +3829,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); diff --git a/server/src/com/cloud/servlet/ConsoleProxyServlet.java b/server/src/com/cloud/servlet/ConsoleProxyServlet.java index 8e5dfbef12d..bf021ea4030 100644 --- a/server/src/com/cloud/servlet/ConsoleProxyServlet.java +++ b/server/src/com/cloud/servlet/ConsoleProxyServlet.java @@ -518,7 +518,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()) { diff --git a/server/src/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/com/cloud/storage/VolumeApiServiceImpl.java index 06773c76a35..150daeced94 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; @@ -265,7 +264,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); @@ -375,11 +374,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 "); @@ -507,6 +505,8 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic // purposes provisioningType = diskOffering.getProvisioningType(); + // check snapshot permissions + _accountMgr.checkAccess(caller, null, true, snapshotCheck); // one step operation - create volume in VM's cluster and attach it // to the VM @@ -522,6 +522,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); } } @@ -769,7 +772,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(); @@ -932,7 +935,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."); @@ -1137,8 +1140,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, volumeToAttach, vm); + _accountMgr.checkAccess(caller, null, true, volumeToAttach, vm); if (!(Volume.State.Allocated.equals(volumeToAttach.getState()) || Volume.State.Ready.equals(volumeToAttach.getState()) || Volume.State.Uploaded.equals(volumeToAttach .getState()))) { @@ -1361,7 +1363,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 currently attached to a VM @@ -1828,7 +1830,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."); diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index d19a0ed8466..44bce1a738e 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 tags = cmd.getTags(); Long zoneId = cmd.getZoneId(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); - // 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 domainIdRecursiveListProject = new Ternary(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 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 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, Integer> result = _snapshotPolicyDao.listAndCountByVolumeId(volumeId); return new Pair, 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()); diff --git a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java index cac12c628d6..fa7fcb750c5 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()) { diff --git a/server/src/com/cloud/template/TemplateAdapterBase.java b/server/src/com/cloud/template/TemplateAdapterBase.java index cb38075324f..fcf15df675b 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 diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index ead841fb1c6..33a6df8a4af 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 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, null, template); + _accountMgr.checkAccess(caller, null, true, template); } List accountNames = new ArrayList(); @@ -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"); diff --git a/server/src/com/cloud/user/AccountManager.java b/server/src/com/cloud/user/AccountManager.java index 03bf8421a30..bee70290418 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 sb, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + + void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + + void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria, List grantedIds, List revokedIds); + + void buildACLSearchCriteria(SearchCriteria sc, + Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + + void buildACLSearchParameters(Account caller, Long id, + String accountName, Long projectId, List permittedAccounts, Ternary domainIdRecursiveListProject, boolean listAll, + boolean forProjectInvitation); + + void buildACLViewSearchCriteria(SearchCriteria sc, + Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + + void buildACLViewSearchCriteria(SearchCriteria sc, + Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria, List grantedIds, + List revokedIds); + + // new ACL model routine for query api based on db views void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List permittedDomains, List permittedAccounts, List permittedResources, Ternary domainIdRecursiveListProject, boolean listAll, boolean forProjectInvitation, String action); - void buildACLSearchBuilder(SearchBuilder sb, boolean isRecursive, - List permittedDomains, - List permittedAccounts, List permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria); - - void buildACLSearchCriteria(SearchCriteria sc, boolean isRecursive, - List permittedDomains, - List permittedAccounts, List permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria); - void buildACLViewSearchCriteria(SearchCriteria sc, SearchCriteria aclSc, boolean isRecursive, List permittedDomains, List permittedAccounts, List permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria); diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index a2f3b098bc0..8c44d5fb65e 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -46,8 +46,8 @@ import org.apache.cloudstack.acl.QuerySelector; import org.apache.cloudstack.acl.RoleType; 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; @@ -60,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; @@ -88,6 +90,7 @@ import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; import com.cloud.network.IpAddressManager; +import com.cloud.network.Network; import com.cloud.network.VpnUserVO; import com.cloud.network.as.AutoScaleManager; import com.cloud.network.dao.AccountGuestVlanMapDao; @@ -107,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; @@ -122,6 +126,7 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.template.TemplateManager; +import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account.State; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserAccountDao; @@ -378,8 +383,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; } @@ -401,8 +406,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; } @@ -432,8 +437,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; } @@ -473,34 +478,91 @@ 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 - StringBuilder entityBuf = new StringBuilder("{"); - for (ControlledEntity ent : entities) { - entityBuf.append(ent); + 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 (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; + } + } } - entityBuf.append("}"); - String entityStr = entityBuf.toString(); - for (SecurityChecker checker : _securityCheckers) { - if (checker.checkAccess(caller, accessType, apiName, entities)) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Access to " + entityStr + " granted to " + caller + " by " + checker.getName()); + + 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> domains = new HashMap>(); + + 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; + } + if (entity.getAccountId() != -1 && domainId != -1 && !(entity instanceof VirtualMachineTemplate) && + !(entity instanceof Network && accessType != null && accessType == AccessType.UseEntry) && !(entity instanceof AffinityGroup)) { + List toBeChecked = domains.get(entity.getDomainId()); + // for templates, we don't have to do cross domains check + if (toBeChecked == null) { + toBeChecked = new ArrayList(); + domains.put(domainId, toBeChecked); + } + toBeChecked.add(entity); + } + boolean granted = false; + for (SecurityChecker checker : _securityCheckers) { + if (checker.checkAccess(caller, entity, accessType, apiName)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Access to " + entity + " granted to " + caller + " by " + checker.getName()); + } + granted = true; + break; } 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> 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 + } @Override @@ -1080,7 +1142,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()) { @@ -1197,7 +1259,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) { @@ -1238,7 +1300,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() { @Override @@ -1290,7 +1352,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 @@ -1353,7 +1415,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()) { @@ -1398,7 +1460,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) { @@ -1432,7 +1494,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()); @@ -1462,7 +1524,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()); @@ -1581,7 +1643,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); } @@ -2190,6 +2252,373 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M } + + @Override + public void buildACLSearchBuilder(SearchBuilder sb, + Long domainId, boolean isRecursive, List 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 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 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 sc, + Long domainId, boolean isRecursive, List 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 +// permittedAccounts, Ternary 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 + permittedAccounts, Ternary 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 sb, Long domainId, + boolean isRecursive, List 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 sb, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria, List grantedIds, List 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 sc, + Long domainId, boolean isRecursive, List 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 sc, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria, List grantedIds, List 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); @@ -2233,8 +2662,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()); } @@ -2347,120 +2776,6 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M } } - @Override - public void buildACLSearchBuilder(SearchBuilder sb, boolean isRecursive, - List permittedDomains, - List permittedAccounts, List permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria) { - - if (listProjectResourcesCriteria != null) { - // add criteria for project or not - SearchBuilder 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 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 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 sc, boolean isRecursive, - List permittedDomains, - List permittedAccounts, List 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 sc, SearchCriteria aclSc, boolean isRecursive, List permittedDomains, diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 11cea13a4bc..f699ee1ff0c 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -35,6 +35,9 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; + import org.apache.cloudstack.acl.ControlledEntity.ACLType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.affinity.AffinityGroupService; @@ -83,8 +86,6 @@ import org.apache.cloudstack.storage.command.DeleteCommand; import org.apache.cloudstack.storage.command.DettachCommand; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -531,7 +532,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state"); } - _accountMgr.checkAccess(caller, null, userVm); + _accountMgr.checkAccess(caller, null, true, userVm); boolean result = resetVMPasswordInternal(vmId, password); @@ -637,7 +638,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir + " in specified domain id"); } - _accountMgr.checkAccess(caller, null, userVm); + _accountMgr.checkAccess(caller, null, true, userVm); String password = null; String sshPublicKey = s.getPublicKey(); if (template != null && template.getEnablePassword()) { @@ -777,7 +778,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir + "; make sure the virtual machine is stopped"); } - _accountMgr.checkAccess(caller, null, vmInstance); + _accountMgr.checkAccess(caller, null, true, vmInstance); // Check resource limits for CPU and Memory. Map customParameters = cmd.getDetails(); @@ -891,7 +892,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); } - _accountMgr.checkAccess(caller, null, vmInstance); + _accountMgr.checkAccess(caller, null, true, vmInstance); // Check resource limits for CPU and Memory. ServiceOfferingVO newServiceOffering = _offeringDao.findById(svcOffId); @@ -960,6 +961,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir Long vmId = cmd.getVmId(); Long networkId = cmd.getNetworkId(); String ipAddress = cmd.getIpAddress(); + Account caller = CallContext.current().getCallingAccount(); UserVmVO vmInstance = _vmDao.findById(vmId); if (vmInstance == null) { @@ -970,6 +972,12 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("unable to find a network with id " + networkId); } + if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) + && !(network.getAclType() == ACLType.Account && network.getAccountId() == vmInstance.getAccountId())) { + throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vmId: " + vmId); + } + } List allNics = _nicDao.listByVmId(vmInstance.getId()); for (NicVO nic : allNics) { @@ -982,12 +990,18 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir profile = new NicProfile(ipAddress, null); } + // Perform permission check on VM + _accountMgr.checkAccess(caller, null, true, vmInstance); + // Verify that zone is not Basic DataCenterVO dc = _dcDao.findById(vmInstance.getDataCenterId()); if (dc.getNetworkType() == DataCenter.NetworkType.Basic) { throw new CloudRuntimeException("Zone " + vmInstance.getDataCenterId() + ", has a NetworkType of Basic. Can't add a new NIC to a VM on a Basic Network"); } + // Perform account permission check on network + _accountMgr.checkAccess(caller, AccessType.UseEntry, false, network); + //ensure network belongs in zone if (network.getDataCenterId() != vmInstance.getDataCenterId()) { throw new CloudRuntimeException(vmInstance + " is in zone:" + vmInstance.getDataCenterId() + " but " + network + " is in zone:" + network.getDataCenterId()); @@ -1046,7 +1060,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // Perform permission check on VM - _accountMgr.checkAccess(caller, null, vmInstance); + _accountMgr.checkAccess(caller, null, true, vmInstance); // Verify that zone is not Basic DataCenterVO dc = _dcDao.findById(vmInstance.getDataCenterId()); @@ -1060,7 +1074,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // Perform account permission check on network - _accountMgr.checkAccess(caller, AccessType.UseEntry, network); + _accountMgr.checkAccess(caller, AccessType.UseEntry, false, network); boolean nicremoved = false; @@ -1102,7 +1116,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // Perform permission check on VM - _accountMgr.checkAccess(caller, null, vmInstance); + _accountMgr.checkAccess(caller, null, true, vmInstance); // Verify that zone is not Basic DataCenterVO dc = _dcDao.findById(vmInstance.getDataCenterId()); @@ -1284,7 +1298,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("This operation not permitted for this hypervisor of the vm"); } - _accountMgr.checkAccess(caller, null, vmInstance); + _accountMgr.checkAccess(caller, null, true, vmInstance); //Check if its a scale "up" ServiceOfferingVO newServiceOffering = _offeringDao.findById(newServiceOfferingId); @@ -1493,7 +1507,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // check permissions - _accountMgr.checkAccess(caller, null, vm); + _accountMgr.checkAccess(caller, null, true, vm); if (vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { @@ -1836,7 +1850,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("unable to find virtual machine with id " + id); } - _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, vmInstance); + _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, vmInstance); //If the flag is specified and is changed if (isDisplayVm != null && isDisplayVm != vmInstance.isDisplayVm()) { @@ -2059,7 +2073,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); } - _accountMgr.checkAccess(caller, null, vmInstance); + _accountMgr.checkAccess(caller, null, true, vmInstance); // If the VM is Volatile in nature, on reboot discard the VM's root disk and create a new root disk for it: by calling restoreVM long serviceOfferingId = vmInstance.getServiceOfferingId(); @@ -2157,7 +2171,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("unable to find a vm group with id " + groupId); } - _accountMgr.checkAccess(caller, null, group); + _accountMgr.checkAccess(caller, null, true, group); return deleteVmGroup(groupId); } @@ -2291,7 +2305,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir List networkList = new ArrayList(); // Verify that caller can perform actions in behalf of vm owner - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, true, owner); // Get default guest network in Basic zone Network defaultNetwork = _networkModel.getExclusiveGuestNetwork(zone.getId()); @@ -2346,7 +2360,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor != null && hypervisor == HypervisorType.VMware)); // Verify that caller can perform actions in behalf of vm owner - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, true, owner); // If no network is specified, find system security group enabled network if (networkIdList == null || networkIdList.isEmpty()) { @@ -2404,7 +2418,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // Perform account permission check if (network.getAclType() == ACLType.Account) { - _accountMgr.checkAccess(owner, AccessType.UseEntry, network); + _accountMgr.checkAccess(caller, AccessType.UseEntry, false, network); } networkList.add(network); } @@ -2450,7 +2464,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir List networkList = new ArrayList(); // Verify that caller can perform actions in behalf of vm owner - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, true, owner); List vpcSupportedHTypes = _vpcMgr.getSupportedVpcHypervisors(); if (networkIdList == null || networkIdList.isEmpty()) { @@ -2544,7 +2558,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir List affinityGroupIdList, Map customParameters, String customId) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException { - _accountMgr.checkAccess(caller, null, owner); + _accountMgr.checkAccess(caller, null, true, owner); if (owner.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of vm to deploy is disabled: " + owner); @@ -2620,7 +2634,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("Unable to find security group by id " + securityGroupId); } else { // verify permissions - _accountMgr.checkAccess(owner, AccessType.UseEntry, sg); + _accountMgr.checkAccess(caller, null, true, owner, sg); } } } @@ -2636,7 +2650,27 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir + " , Please try again after removing the affinity group"); } else { // verify permissions - _accountMgr.checkAccess(owner, AccessType.UseEntry, ag); + if (ag.getAclType() == ACLType.Domain) { + _accountMgr.checkAccess(caller, null, false, owner, ag); + // Root admin has access to both VM and AG by default, + // but + // make sure the owner of these entities is same + if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) { + if (!_affinityGroupService.isAffinityGroupAvailableInDomain(ag.getId(), owner.getDomainId())) { + throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain"); + } + } + } else { + _accountMgr.checkAccess(caller, null, true, owner, ag); + // Root admin has access to both VM and AG by default, + // but + // make sure the owner of these entities is same + if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) { + if (ag.getAccountId() != owner.getAccountId()) { + throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's account"); + } + } + } } } } @@ -2662,7 +2696,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // Check templates permissions - _accountMgr.checkAccess(owner, AccessType.UseEntry, template); + if (!template.isPublicTemplate()) { + Account templateOwner = _accountMgr.getAccount(template.getAccountId()); + _accountMgr.checkAccess(owner, null, true, templateOwner); + } // check if the user data is correct validateUserData(userData, httpmethod); @@ -2691,8 +2728,14 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId()); } - // Perform account permission check on network - _accountMgr.checkAccess(owner, AccessType.UseEntry, network); + //relax the check if the caller is admin account + if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) + && !(network.getAclType() == ACLType.Account && network.getAccountId() == accountId)) { + throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vm"); + } + } + IpAddresses requestedIpPair = null; if (requestedIps != null && !requestedIps.isEmpty()) { requestedIpPair = requestedIps.get(network.getId()); @@ -3314,7 +3357,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); } - _accountMgr.checkAccess(callerAccount, null, vm); + _accountMgr.checkAccess(callerAccount, null, true, vm); Account owner = _accountDao.findById(vm.getAccountId()); @@ -3621,7 +3664,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw ex; } - _accountMgr.checkAccess(caller, null, vm); + _accountMgr.checkAccess(caller, null, true, vm); boolean status; @@ -4202,8 +4245,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } //check caller has access to both the old and new account - _accountMgr.checkAccess(caller, null, oldAccount); - _accountMgr.checkAccess(caller, null, newAccount); + _accountMgr.checkAccess(caller, null, true, oldAccount); + _accountMgr.checkAccess(caller, null, true, newAccount); // make sure the accounts are not same if (oldAccount.getAccountId() == newAccount.getAccountId()) { @@ -4256,7 +4299,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir VirtualMachineTemplate template = _templateDao.findById(vm.getTemplateId()); if (!template.isPublicTemplate()) { Account templateOwner = _accountMgr.getAccount(template.getAccountId()); - _accountMgr.checkAccess(newAccount, null, templateOwner); + _accountMgr.checkAccess(newAccount, null, true, templateOwner); } // VV 5: check the new account can create vm in the domain @@ -4513,7 +4556,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw ex; } - _accountMgr.checkAccess(caller, null, vm); + _accountMgr.checkAccess(caller, null, true, vm); return restoreVMInternal(caller, vm, newTemplateId); } @@ -4563,7 +4606,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir //newTemplateId can be either template or ISO id. In the following snippet based on the vm deployment (from template or ISO) it is handled accordingly if (newTemplateId != null) { template = _templateDao.findById(newTemplateId); - _accountMgr.checkAccess(caller, null, template); + _accountMgr.checkAccess(caller, null, true, template); if (isISO) { if (!template.getFormat().equals(ImageFormat.ISO)) { throw new InvalidParameterValueException("Invalid ISO id provided to restore the VM "); @@ -4744,7 +4787,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // root.getPoolId() should be null if the VM we are detaching the disk from has never been started before DataStore dataStore = root.getPoolId() != null ? _dataStoreMgr.getDataStore(root.getPoolId(), DataStoreRole.Primary) : null; - volumeMgr.disconnectVolumeFromHost(volFactory.getVolume(root.getId()), host, dataStore); } } @@ -4792,7 +4834,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } //check permissions - _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, vm); + _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, vm); return vm.getUserData(); } diff --git a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java index 7a2d0ade11f..3238cb5422c 100644 --- a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java +++ b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java @@ -169,9 +169,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana @Override public List listVMSnapshots(ListVMSnapshotCmd cmd) { Account caller = getCaller(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); boolean listAll = cmd.listAll(); Long id = cmd.getId(); @@ -184,14 +182,15 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana Ternary domainIdRecursiveListProject = new Ternary( cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, listAll, false, "listVMSnapshot"); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, + false); + Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(VMSnapshotVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _vmSnapshotDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("vm_id", sb.entity().getVmId(), SearchCriteria.Op.EQ); sb.and("domain_id", sb.entity().getDomainId(), SearchCriteria.Op.EQ); @@ -203,7 +202,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana sb.done(); SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (accountName != null && cmd.getDomainId() != null) { Account account = _accountMgr.getActiveAccountByName(accountName, cmd.getDomainId()); @@ -214,8 +213,8 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana sc.setParameters("vm_id", vmId); } - if (cmd.getDomainId() != null) { - sc.setParameters("domain_id", cmd.getDomainId()); + if (domainId != null) { + sc.setParameters("domain_id", domainId); } if (state == null) { @@ -297,7 +296,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana } // check access - //_accountMgr.checkAccess(caller, null, userVmVo); + _accountMgr.checkAccess(caller, null, true, userVmVo); // check max snapshot limit for per VM if (_vmSnapshotDao.findByVm(vmId).size() >= _vmSnapshotMax) { @@ -448,7 +447,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana throw new InvalidParameterValueException("unable to find the vm snapshot with id " + vmSnapshotId); } - _accountMgr.checkAccess(caller, null, vmSnapshot); + _accountMgr.checkAccess(caller, null, true, vmSnapshot); // check VM snapshot states, only allow to delete vm snapshots in created and error state if (VMSnapshot.State.Ready != vmSnapshot.getState() && VMSnapshot.State.Expunging != vmSnapshot.getState() && VMSnapshot.State.Error != vmSnapshot.getState()) { @@ -513,7 +512,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana throw new InvalidParameterValueException("unable to find the vm snapshot with id " + vmSnapshotId); } - _accountMgr.checkAccess(caller, null, vmSnapshot); + _accountMgr.checkAccess(caller, null, true, vmSnapshot); // check VM snapshot states, only allow to delete vm snapshots in created and error state if (VMSnapshot.State.Ready != vmSnapshot.getState() && VMSnapshot.State.Expunging != vmSnapshot.getState() && VMSnapshot.State.Error != vmSnapshot.getState()) { @@ -564,7 +563,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana } Account caller = getCaller(); - _accountMgr.checkAccess(caller, null, vmSnapshotVo); + _accountMgr.checkAccess(caller, null, true, vmSnapshotVo); // VM should be in running or stopped states if (userVm.getState() != VirtualMachine.State.Running @@ -646,7 +645,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana } Account caller = getCaller(); - _accountMgr.checkAccess(caller, null, vmSnapshotVo); + _accountMgr.checkAccess(caller, null, true, vmSnapshotVo); // VM should be in running or stopped states if (userVm.getState() != VirtualMachine.State.Running && userVm.getState() != VirtualMachine.State.Stopped) { diff --git a/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java b/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java index ef636920cd9..8e606ca0584 100644 --- a/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java +++ b/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java @@ -262,7 +262,7 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro affinityGroupId = group.getId(); } // check permissions - _accountMgr.checkAccess(caller, AccessType.OperateEntry, group); + _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, group); final Long affinityGroupIdFinal = affinityGroupId; Transaction.execute(new TransactionCallbackNoReturn() { @@ -353,7 +353,7 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro if (userVM == null) { throw new InvalidParameterValueException("Unable to list affinity groups for virtual machine instance " + vmId + "; instance not found."); } - _accountMgr.checkAccess(caller, null, userVM); + _accountMgr.checkAccess(caller, null, true, userVM); // add join to affinity_groups_vm_map groupSearch.join("vmInstanceSearch", vmInstanceSearch, groupSearch.entity().getId(), vmInstanceSearch.entity().getAffinityGroupId(), JoinBuilder.JoinType.INNER); @@ -477,7 +477,14 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupId); } else { // verify permissions - _accountMgr.checkAccess(owner, AccessType.UseEntry, ag); + _accountMgr.checkAccess(caller, null, true, owner, ag); + // Root admin has access to both VM and AG by default, but make sure the + // owner of these entities is same + if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) { + if (ag.getAccountId() != owner.getAccountId()) { + throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's account"); + } + } } } _affinityGroupVMMapDao.updateMap(vmId, affinityGroupIds); diff --git a/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java b/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java index ad1a2c4ec83..6854347ba62 100644 --- a/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java +++ b/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java @@ -115,7 +115,7 @@ public class ApplicationLoadBalancerManagerImpl extends ManagerBase implements A } Account caller = CallContext.current().getCallingAccount(); - _accountMgr.checkAccess(caller, AccessType.UseEntry, guestNtwk); + _accountMgr.checkAccess(caller, AccessType.UseEntry, false, guestNtwk); Network sourceIpNtwk = _networkModel.getNetwork(sourceIpNetworkId); if (sourceIpNtwk == null) { @@ -389,20 +389,19 @@ public class ApplicationLoadBalancerManagerImpl extends ManagerBase implements A Map tags = cmd.getTags(); Account caller = CallContext.current().getCallingAccount(); - List permittedDomains = new ArrayList(); List permittedAccounts = new ArrayList(); - List permittedResources = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary( cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources, - domainIdRecursiveListProject, cmd.listAll(), false, "listLoadBalancers"); + _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(ApplicationLoadBalancerRuleVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _lbDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); @@ -429,7 +428,7 @@ public class ApplicationLoadBalancerManagerImpl extends ManagerBase implements A } SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (keyword != null) { SearchCriteria ssc = _lbDao.createSearchCriteria(); @@ -547,7 +546,7 @@ public class ApplicationLoadBalancerManagerImpl extends ManagerBase implements A if (rule == null) { throw new InvalidParameterValueException("Unable to find load balancer " + id); } - _accountMgr.checkAccess(caller, null, rule); + _accountMgr.checkAccess(caller, null, true, rule); if (customId != null) { rule.setUuid(customId); diff --git a/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java b/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java index 67f2c02e0ca..ba71d631a94 100644 --- a/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java +++ b/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java @@ -147,7 +147,7 @@ public class CertServiceImpl implements CertService { if (certVO == null) { throw new InvalidParameterValueException("Invalid certificate id: " + certId); } - _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, certVO); + _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, certVO); List lbCertRule = _lbCertDao.listByCertId(certId); @@ -191,7 +191,7 @@ public class CertServiceImpl implements CertService { throw new InvalidParameterValueException("Invalid certificate id: " + certId); } - _accountMgr.checkAccess(caller, SecurityChecker.AccessType.UseEntry, certVO); + _accountMgr.checkAccess(caller, SecurityChecker.AccessType.UseEntry, true, certVO); certLbMap = _lbCertDao.listByCertId(certId); @@ -206,7 +206,7 @@ public class CertServiceImpl implements CertService { throw new InvalidParameterValueException("found no loadbalancer wth id: " + lbRuleId); } - _accountMgr.checkAccess(caller, SecurityChecker.AccessType.UseEntry, lb); + _accountMgr.checkAccess(caller, SecurityChecker.AccessType.UseEntry, true, lb); // get the cert id LoadBalancerCertMapVO lbCertMapRule; @@ -229,7 +229,7 @@ public class CertServiceImpl implements CertService { List certVOList = _sslCertDao.listByAccountId(accountId); if (certVOList == null || certVOList.isEmpty()) return certResponseList; - _accountMgr.checkAccess(caller, SecurityChecker.AccessType.UseEntry, certVOList.get(0)); + _accountMgr.checkAccess(caller, SecurityChecker.AccessType.UseEntry, true, certVOList.get(0)); for (SslCertVO cert : certVOList) { certLbMap = _lbCertDao.listByCertId(cert.getId()); diff --git a/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java b/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java index 516b3ab5215..c84fea29d5e 100644 --- a/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java +++ b/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java @@ -183,7 +183,7 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId); } - _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, gslbRule); + _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, gslbRule); if (gslbRule.getState() == GlobalLoadBalancerRule.State.Revoke) { throw new InvalidParameterValueException("global load balancer rule id: " + gslbRule.getUuid() + " is in revoked state"); @@ -224,7 +224,7 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR throw new InvalidParameterValueException("Specified load balancer rule ID does not exist."); } - _accountMgr.checkAccess(caller, null, loadBalancer); + _accountMgr.checkAccess(caller, null, true, loadBalancer); if (gslbRule.getAccountId() != loadBalancer.getAccountId()) { throw new InvalidParameterValueException("GSLB rule and load balancer rule does not belong to same account"); @@ -319,7 +319,7 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId); } - _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, gslbRule); + _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, gslbRule); if (gslbRule.getState() == GlobalLoadBalancerRule.State.Revoke) { throw new InvalidParameterValueException("global load balancer rule id: " + gslbRuleId + " is already in revoked state"); @@ -346,7 +346,7 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR throw new InvalidParameterValueException("Specified load balancer rule ID does not exist."); } - _accountMgr.checkAccess(caller, null, loadBalancer); + _accountMgr.checkAccess(caller, null, true, loadBalancer); } for (GlobalLoadBalancerLbRuleMapVO gslbLbMapVo : gslbLbMapVos) { @@ -445,7 +445,7 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId); } - _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, gslbRule); + _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, gslbRule); if (gslbRule.getState() == com.cloud.region.ha.GlobalLoadBalancerRule.State.Staged) { if (s_logger.isDebugEnabled()) { @@ -523,7 +523,7 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR CallContext ctx = CallContext.current(); Account caller = ctx.getCallingAccount(); - _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, gslbRule); + _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, gslbRule); if (algorithm != null && !GlobalLoadBalancerRule.Algorithm.isValidAlgorithm(algorithm)) { throw new InvalidParameterValueException("Invalid Algorithm: " + algorithm); @@ -583,7 +583,7 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR if (gslbRule == null) { throw new InvalidParameterValueException("Invalid gslb rule id specified"); } - _accountMgr.checkAccess(caller, org.apache.cloudstack.acl.SecurityChecker.AccessType.UseEntry, gslbRule); + _accountMgr.checkAccess(caller, org.apache.cloudstack.acl.SecurityChecker.AccessType.UseEntry, false, gslbRule); response.add(gslbRule); return response; diff --git a/server/test/com/cloud/event/EventControlsUnitTest.java b/server/test/com/cloud/event/EventControlsUnitTest.java index 0dc57427c5a..91dc921d261 100644 --- a/server/test/com/cloud/event/EventControlsUnitTest.java +++ b/server/test/com/cloud/event/EventControlsUnitTest.java @@ -60,7 +60,7 @@ public class EventControlsUnitTest extends TestCase { MockitoAnnotations.initMocks(this); _mgmtServer._eventDao = _eventDao; _mgmtServer._accountMgr = _accountMgr; - doNothing().when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(ControlledEntity.class)); + doNothing().when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(Boolean.class), any(ControlledEntity.class)); when(_eventDao.listToArchiveOrDeleteEvents(anyList(), anyString(), any(Date.class), any(Date.class), anyList())).thenReturn(_events); } diff --git a/server/test/com/cloud/network/MockNetworkModelImpl.java b/server/test/com/cloud/network/MockNetworkModelImpl.java index f4f04da327a..57ad92e8ee4 100644 --- a/server/test/com/cloud/network/MockNetworkModelImpl.java +++ b/server/test/com/cloud/network/MockNetworkModelImpl.java @@ -25,8 +25,6 @@ import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; - import com.cloud.dc.Vlan; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -890,10 +888,4 @@ public class MockNetworkModelImpl extends ManagerBase implements NetworkModel { return false; //To change body of implemented methods use File | Settings | File Templates. } - @Override - public void checkNetworkPermissions(Account owner, Network network, AccessType accessType) { - // TODO Auto-generated method stub - - } - } diff --git a/server/test/com/cloud/storage/VolumeApiServiceImplTest.java b/server/test/com/cloud/storage/VolumeApiServiceImplTest.java index 68931a192d3..c60aa503451 100644 --- a/server/test/com/cloud/storage/VolumeApiServiceImplTest.java +++ b/server/test/com/cloud/storage/VolumeApiServiceImplTest.java @@ -233,7 +233,7 @@ public class VolumeApiServiceImplTest { } // helper methods mock - doNothing().when(_svc._accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(ControlledEntity.class)); + doNothing().when(_svc._accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(Boolean.class), any(ControlledEntity.class)); doNothing().when(_svc._jobMgr).updateAsyncJobAttachment(any(Long.class), any(String.class), any(Long.class)); when(_svc._jobMgr.submitAsyncJob(any(AsyncJobVO.class), any(String.class), any(Long.class))).thenReturn(1L); } diff --git a/server/test/com/cloud/user/MockAccountManagerImpl.java b/server/test/com/cloud/user/MockAccountManagerImpl.java index a2b8a8559ff..cc8fbacfb70 100644 --- a/server/test/com/cloud/user/MockAccountManagerImpl.java +++ b/server/test/com/cloud/user/MockAccountManagerImpl.java @@ -32,6 +32,7 @@ import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; import org.apache.cloudstack.api.command.admin.user.RegisterCmd; import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; +import com.cloud.api.query.vo.ControlledViewEntity; import com.cloud.domain.Domain; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.PermissionDeniedException; @@ -218,6 +219,10 @@ public class MockAccountManagerImpl extends ManagerBase implements Manager, Acco return null; } + @Override + public void checkAccess(Account account, AccessType accessType, boolean sameOwner, ControlledEntity... entities) throws PermissionDeniedException { + // TODO Auto-generated method stub + } @Override @@ -252,6 +257,50 @@ public class MockAccountManagerImpl extends ManagerBase implements Manager, Acco return false; } + @Override + public void buildACLSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List permittedAccounts, Ternary domainIdRecursiveListProject, boolean listAll, boolean forProjectInvitation) { + // TODO Auto-generated method stub + } + + @Override + public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + // TODO Auto-generated method stub + } + + @Override + public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria, List grantedIds, List revokedIds) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLViewSearchCriteria(SearchCriteria sc, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + // TODO Auto-generated method stub + } + + @Override + public void buildACLViewSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria, List grantedIds, List revokedIds) { + // TODO Auto-generated method stub + + } /* (non-Javadoc) * @see com.cloud.user.AccountService#getUserByApiKey(java.lang.String) @@ -320,19 +369,6 @@ public class MockAccountManagerImpl extends ManagerBase implements Manager, Acco } - @Override - public void buildACLSearchBuilder(SearchBuilder sb, boolean isRecursive, List permittedDomains, List permittedAccounts, - List permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria) { - // TODO Auto-generated method stub - - } - - @Override - public void buildACLSearchCriteria(SearchCriteria sc, boolean isRecursive, List permittedDomains, List permittedAccounts, - List permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria) { - // TODO Auto-generated method stub - - } @Override public List listAclGroupsByAccount(Long accountId) { @@ -340,6 +376,11 @@ public class MockAccountManagerImpl extends ManagerBase implements Manager, Acco return null; } + @Override + public void checkAccess(Account account, AccessType accessType, boolean sameOwner, String apiName, + ControlledEntity... entities) throws PermissionDeniedException { + // TODO Auto-generated method stub + } @Override public Long finalyzeAccountId(String accountName, Long domainId, Long projectId, boolean enabledOnly) { @@ -347,15 +388,5 @@ public class MockAccountManagerImpl extends ManagerBase implements Manager, Acco return null; } - @Override - public void checkAccess(Account account, AccessType accessType, ControlledEntity... entities) throws PermissionDeniedException { - // TODO Auto-generated method stub - } - - @Override - public void checkAccess(Account account, AccessType accessType, String apiName, ControlledEntity... entities) throws PermissionDeniedException { - // TODO Auto-generated method stub - - } } diff --git a/server/test/com/cloud/vm/UserVmManagerTest.java b/server/test/com/cloud/vm/UserVmManagerTest.java index b07f7257591..a69f270e925 100755 --- a/server/test/com/cloud/vm/UserVmManagerTest.java +++ b/server/test/com/cloud/vm/UserVmManagerTest.java @@ -284,7 +284,7 @@ public class UserVmManagerTest { doReturn(3L).when(_volumeMock).getTemplateId(); doReturn(ImageFormat.VHD).when(_templateMock).getFormat(); when(_templateDao.findById(anyLong())).thenReturn(_templateMock); - doNothing().when(_accountMgr).checkAccess(_account, null, _templateMock); + doNothing().when(_accountMgr).checkAccess(_account, null, true, _templateMock); when(_storageMgr.allocateDuplicateVolume(_volumeMock, 14L)).thenReturn(_volumeMock); when(_templateMock.getGuestOSId()).thenReturn(5L); doNothing().when(_vmMock).setGuestOSId(anyLong()); @@ -328,7 +328,7 @@ public class UserVmManagerTest { doReturn(3L).when(_vmMock).getIsoId(); doReturn(ImageFormat.ISO).when(_templateMock).getFormat(); when(_templateDao.findById(anyLong())).thenReturn(_templateMock); - doNothing().when(_accountMgr).checkAccess(_account, null, _templateMock); + doNothing().when(_accountMgr).checkAccess(_account, null, true, _templateMock); when(_storageMgr.allocateDuplicateVolume(_volumeMock, null)).thenReturn(_volumeMock); doNothing().when(_vmMock).setIsoId(14L); when(_templateMock.getGuestOSId()).thenReturn(5L); @@ -414,7 +414,7 @@ public class UserVmManagerTest { doReturn(VirtualMachine.State.Running).when(_vmInstance).getState(); - doNothing().when(_accountMgr).checkAccess(_account, null, _templateMock); + doNothing().when(_accountMgr).checkAccess(_account, null, true, _templateMock); doNothing().when(_itMgr).checkIfCanUpgrade(_vmMock, _offeringVo); @@ -608,7 +608,7 @@ public class UserVmManagerTest { when(_accountService.getActiveAccountByName(anyString(), anyLong())).thenReturn(newAccount); - doThrow(new PermissionDeniedException("Access check failed")).when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class), + doThrow(new PermissionDeniedException("Access check failed")).when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(Boolean.class), any(ControlledEntity.class)); CallContext.register(user, caller); diff --git a/server/test/com/cloud/vm/snapshot/VMSnapshotManagerTest.java b/server/test/com/cloud/vm/snapshot/VMSnapshotManagerTest.java index 03afdbd5804..9d5c2b42ea9 100644 --- a/server/test/com/cloud/vm/snapshot/VMSnapshotManagerTest.java +++ b/server/test/com/cloud/vm/snapshot/VMSnapshotManagerTest.java @@ -125,7 +125,7 @@ public class VMSnapshotManagerTest { _vmSnapshotMgr._guestOSDao = _guestOSDao; _vmSnapshotMgr._hypervisorCapabilitiesDao = _hypervisorCapabilitiesDao; - doNothing().when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(ControlledEntity.class)); + doNothing().when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(Boolean.class), any(ControlledEntity.class)); _vmSnapshotMgr._vmSnapshotMax = _vmSnapshotMax; diff --git a/server/test/com/cloud/vpc/MockNetworkModelImpl.java b/server/test/com/cloud/vpc/MockNetworkModelImpl.java index 49030907b94..49f506549ee 100644 --- a/server/test/com/cloud/vpc/MockNetworkModelImpl.java +++ b/server/test/com/cloud/vpc/MockNetworkModelImpl.java @@ -26,8 +26,6 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; - import com.cloud.dc.Vlan; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -905,10 +903,4 @@ public class MockNetworkModelImpl extends ManagerBase implements NetworkModel { return false; //To change body of implemented methods use File | Settings | File Templates. } - @Override - public void checkNetworkPermissions(Account owner, Network network, AccessType accessType) { - // TODO Auto-generated method stub - - } - } diff --git a/services/iam/plugin/src/org/apache/cloudstack/iam/RoleBasedEntityAccessChecker.java b/services/iam/plugin/src/org/apache/cloudstack/iam/RoleBasedEntityAccessChecker.java index d418c5a6b95..ce9d9755aef 100644 --- a/services/iam/plugin/src/org/apache/cloudstack/iam/RoleBasedEntityAccessChecker.java +++ b/services/iam/plugin/src/org/apache/cloudstack/iam/RoleBasedEntityAccessChecker.java @@ -27,6 +27,7 @@ import org.apache.log4j.Logger; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.PermissionScope; import org.apache.cloudstack.acl.SecurityChecker; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.InternalIdentity; import org.apache.cloudstack.iam.api.IAMGroup; import org.apache.cloudstack.iam.api.IAMPolicy; @@ -212,15 +213,13 @@ public class RoleBasedEntityAccessChecker extends DomainChecker implements Secur boolean otherEntitiesAccess = true; for (ControlledEntity otherEntity : entities) { - if (otherEntity != entity) { - if (otherEntity.getAccountId() == caller.getAccountId() - || (checkAccess(caller, otherEntity, accessType, action) && otherEntity.getAccountId() == entity - .getAccountId())) { - continue; - } else { - otherEntitiesAccess = false; - break; - } + if (otherEntity.getAccountId() == caller.getAccountId() + || (checkAccess(caller, otherEntity, accessType, action) && otherEntity.getAccountId() == entity + .getAccountId())) { + continue; + } else { + otherEntitiesAccess = false; + break; } } @@ -271,8 +270,6 @@ public class RoleBasedEntityAccessChecker extends DomainChecker implements Secur if (_domainDao.isChildDomain(caller.getDomainId(), entity.getDomainId())) { return true; } - } else if (scope.equals(PermissionScope.ALL.name())) { - return true; } } return false; diff --git a/services/iam/plugin/src/org/apache/cloudstack/iam/RoleBasedEntityQuerySelector.java b/services/iam/plugin/src/org/apache/cloudstack/iam/RoleBasedEntityQuerySelector.java index b7c3d352773..a9be17a1cd4 100644 --- a/services/iam/plugin/src/org/apache/cloudstack/iam/RoleBasedEntityQuerySelector.java +++ b/services/iam/plugin/src/org/apache/cloudstack/iam/RoleBasedEntityQuerySelector.java @@ -57,11 +57,9 @@ public class RoleBasedEntityQuerySelector extends AdapterBase implements QuerySe List domainIds = new ArrayList(); for (IAMPolicy policy : policies) { List pp = new ArrayList(); - for (AccessType type : AccessType.values()) { - if (type.ordinal() >= accessType.ordinal()) { - pp.addAll(_iamService.listPolicyPermissionsByScope(policy.getId(), action, PermissionScope.DOMAIN.toString(), type)); - } - } + pp.addAll(_iamService.listPolicyPermissionsByScope(policy.getId(), action, + PermissionScope.DOMAIN.toString(), accessType.toString())); + if (pp != null) { for (IAMPolicyPermission p : pp) { if (p.getScopeId() != null) { @@ -101,11 +99,9 @@ public class RoleBasedEntityQuerySelector extends AdapterBase implements QuerySe List accountIds = new ArrayList(); for (IAMPolicy policy : policies) { List pp = new ArrayList(); - for (AccessType type : AccessType.values()) { - if (type.ordinal() >= accessType.ordinal()) { - pp.addAll(_iamService.listPolicyPermissionsByScope(policy.getId(), action, PermissionScope.ACCOUNT.toString(), type)); - } - } + pp.addAll(_iamService.listPolicyPermissionsByScope(policy.getId(), action, + PermissionScope.ACCOUNT.toString(), accessType.toString())); + if (pp != null) { for (IAMPolicyPermission p : pp) { if (p.getScopeId() != null) { @@ -144,11 +140,9 @@ public class RoleBasedEntityQuerySelector extends AdapterBase implements QuerySe List entityIds = new ArrayList(); for (IAMPolicy policy : policies) { List pp = new ArrayList(); - for (AccessType type : AccessType.values()) { - if (type.ordinal() >= accessType.ordinal()) { - pp.addAll(_iamService.listPolicyPermissionsByScope(policy.getId(), action, PermissionScope.RESOURCE.toString(), type)); - } - } + pp.addAll(_iamService.listPolicyPermissionsByScope(policy.getId(), action, + PermissionScope.RESOURCE.toString(), accessType.toString())); + if (pp != null) { for (IAMPolicyPermission p : pp) { if (p.getScopeId() != null) { @@ -171,13 +165,10 @@ public class RoleBasedEntityQuerySelector extends AdapterBase implements QuerySe // for each policy, find granted permission with ALL scope for (IAMPolicy policy : policies) { List pp = new ArrayList(); - for (AccessType type : AccessType.values()) { - if (type.ordinal() >= accessType.ordinal()) { - pp.addAll(_iamService.listPolicyPermissionsByScope(policy.getId(), action, PermissionScope.ALL.toString(), type)); - } - if (pp != null && pp.size() > 0) { - return true; - } + pp.addAll(_iamService.listPolicyPermissionsByScope(policy.getId(), action, PermissionScope.ALL.toString(), + accessType.toString())); + if (pp != null && pp.size() > 0) { + return true; } } return false; @@ -194,3 +185,4 @@ public class RoleBasedEntityQuerySelector extends AdapterBase implements QuerySe } } + diff --git a/services/iam/server/src/org/apache/cloudstack/iam/api/IAMService.java b/services/iam/server/src/org/apache/cloudstack/iam/api/IAMService.java index 0c0e9c6aad5..3a470ee677f 100644 --- a/services/iam/server/src/org/apache/cloudstack/iam/api/IAMService.java +++ b/services/iam/server/src/org/apache/cloudstack/iam/api/IAMService.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.iam.api; import java.util.List; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.iam.api.IAMPolicyPermission.Permission; import com.cloud.utils.Pair; @@ -73,7 +72,7 @@ public interface IAMService { List listPolicyPermissions(long policyId); - List listPolicyPermissionsByScope(long policyId, String action, String scope, AccessType accessType); + List listPolicyPermissionsByScope(long policyId, String action, String scope, String accessType); List listPolicyPermissionByActionAndEntity(long policyId, String action, String entityType); diff --git a/services/iam/server/src/org/apache/cloudstack/iam/server/IAMServiceImpl.java b/services/iam/server/src/org/apache/cloudstack/iam/server/IAMServiceImpl.java index 33869c8b1f5..fa37cf621e2 100644 --- a/services/iam/server/src/org/apache/cloudstack/iam/server/IAMServiceImpl.java +++ b/services/iam/server/src/org/apache/cloudstack/iam/server/IAMServiceImpl.java @@ -1,903 +1,906 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package org.apache.cloudstack.iam.server; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import net.sf.ehcache.Cache; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Element; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.acl.PermissionScope; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; -import org.apache.cloudstack.iam.api.IAMGroup; -import org.apache.cloudstack.iam.api.IAMPolicy; -import org.apache.cloudstack.iam.api.IAMPolicyPermission; -import org.apache.cloudstack.iam.api.IAMPolicyPermission.Permission; -import org.apache.cloudstack.iam.api.IAMService; -import org.apache.cloudstack.iam.server.dao.IAMAccountPolicyMapDao; -import org.apache.cloudstack.iam.server.dao.IAMGroupAccountMapDao; -import org.apache.cloudstack.iam.server.dao.IAMGroupDao; -import org.apache.cloudstack.iam.server.dao.IAMGroupPolicyMapDao; -import org.apache.cloudstack.iam.server.dao.IAMPolicyDao; -import org.apache.cloudstack.iam.server.dao.IAMPolicyPermissionDao; - -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.Pair; -import com.cloud.utils.component.Manager; -import com.cloud.utils.component.ManagerBase; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.EntityManager; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.GenericSearchBuilder; -import com.cloud.utils.db.JoinBuilder; -import com.cloud.utils.db.JoinBuilder.JoinType; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallback; -import com.cloud.utils.db.TransactionCallbackNoReturn; -import com.cloud.utils.db.TransactionStatus; - -@Local(value = {IAMService.class}) -public class IAMServiceImpl extends ManagerBase implements IAMService, Manager { - - public static final Logger s_logger = Logger.getLogger(IAMServiceImpl.class); - private String _name; - - @Inject - IAMPolicyDao _aclPolicyDao; - - @Inject - IAMGroupDao _aclGroupDao; - - @Inject - EntityManager _entityMgr; - - @Inject - IAMGroupPolicyMapDao _aclGroupPolicyMapDao; - - @Inject - IAMAccountPolicyMapDao _aclAccountPolicyMapDao; - - @Inject - IAMGroupAccountMapDao _aclGroupAccountMapDao; - - @Inject - IAMPolicyPermissionDao _policyPermissionDao; - - private Cache _iamCache; - - private void createIAMCache(final Map params) { - final String value = (String)params.get("cache.size"); - - if (value != null) { - final CacheManager cm = CacheManager.create(); - final int maxElements = NumbersUtil.parseInt(value, 0); - final int live = NumbersUtil.parseInt((String)params.get("cache.time.to.live"), 300); - final int idle = NumbersUtil.parseInt((String)params.get("cache.time.to.idle"), 300); - _iamCache = new Cache(getName(), maxElements, false, live == -1, live == -1 ? Integer.MAX_VALUE : live, idle); - cm.addCache(_iamCache); - s_logger.info("IAM Cache created: " + _iamCache.toString()); - } else { - _iamCache = null; - } - } - - @Override - public void addToIAMCache(Object accessKey, Object allowDeny) { - if (_iamCache != null) { - try { - s_logger.debug("Put IAM access check for " + accessKey + " in cache"); - _iamCache.put(new Element(accessKey, allowDeny)); - } catch (final Exception e) { - s_logger.debug("Can't put " + accessKey + " to IAM cache", e); - } - } - } - - @Override - public void invalidateIAMCache() { - //This may need to use event bus to publish to other MS, but event bus now is missing this functionality to handle PublishScope.GLOBAL - if (_iamCache != null) { - s_logger.debug("Invalidate IAM cache"); - _iamCache.removeAll(); - } - } - - @Override - public Object getFromIAMCache(Object accessKey) { - if (_iamCache != null) { - final Element element = _iamCache.get(accessKey); - return element == null ? null : element.getObjectValue(); - } - return null; - } - - @Override - public boolean configure(final String name, final Map params) throws ConfigurationException { - boolean result = super.configure(name, params); - // create IAM cache - createIAMCache(params); - return result; - } - - @DB - @Override - public IAMGroup createIAMGroup(String iamGroupName, String description, String path) { - // check if the group is already existing - IAMGroup grp = _aclGroupDao.findByName(path, iamGroupName); - if (grp != null) { - throw new InvalidParameterValueException( - "Unable to create acl group with name " + iamGroupName - + " already exisits for path " + path); - } - IAMGroupVO rvo = new IAMGroupVO(iamGroupName, description); - rvo.setPath(path); - - return _aclGroupDao.persist(rvo); - } - - @DB - @Override - public boolean deleteIAMGroup(final Long iamGroupId) { - // get the Acl Group entity - final IAMGroup grp = _aclGroupDao.findById(iamGroupId); - if (grp == null) { - throw new InvalidParameterValueException("Unable to find acl group: " + iamGroupId - + "; failed to delete acl group."); - } - - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - // remove this group related entry in acl_group_policy_map - List groupPolicyMap = _aclGroupPolicyMapDao.listByGroupId(grp.getId()); - if (groupPolicyMap != null) { - for (IAMGroupPolicyMapVO gr : groupPolicyMap) { - _aclGroupPolicyMapDao.remove(gr.getId()); - } - } - - // remove this group related entry in acl_group_account table - List groupAcctMap = _aclGroupAccountMapDao.listByGroupId(grp.getId()); - if (groupAcctMap != null) { - for (IAMGroupAccountMapVO grpAcct : groupAcctMap) { - _aclGroupAccountMapDao.remove(grpAcct.getId()); - } - } - - // remove this group from acl_group table - _aclGroupDao.remove(iamGroupId); - } - }); - - invalidateIAMCache(); - return true; - } - - @SuppressWarnings("unchecked") - @Override - public List listIAMGroups(long accountId) { - - GenericSearchBuilder groupSB = _aclGroupAccountMapDao.createSearchBuilder(Long.class); - groupSB.selectFields(groupSB.entity().getAclGroupId()); - groupSB.and("account", groupSB.entity().getAccountId(), Op.EQ); - SearchCriteria groupSc = groupSB.create(); - groupSc.setParameters("account", accountId); - - List groupIds = _aclGroupAccountMapDao.customSearch(groupSc, null); - - if (groupIds == null || groupIds.isEmpty()) { - return new ArrayList(); - } - SearchBuilder sb = _aclGroupDao.createSearchBuilder(); - sb.and("ids", sb.entity().getId(), Op.IN); - SearchCriteria sc = sb.create(); - sc.setParameters("ids", groupIds.toArray(new Object[groupIds.size()])); - @SuppressWarnings("rawtypes") - List groups = _aclGroupDao.search(sc, null); - return groups; - } - - @DB - @Override - public IAMGroup addAccountsToGroup(final List acctIds, final Long groupId) { - // get the Acl Group entity - IAMGroup group = _aclGroupDao.findById(groupId); - if (group == null) { - throw new InvalidParameterValueException("Unable to find acl group: " + groupId - + "; failed to add accounts to acl group."); - } - - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - // add entries in acl_group_account_map table - for (Long acctId : acctIds) { - // check account permissions - IAMGroupAccountMapVO grMap = _aclGroupAccountMapDao.findByGroupAndAccount(groupId, acctId); - if (grMap == null) { - // not there already - grMap = new IAMGroupAccountMapVO(groupId, acctId); - _aclGroupAccountMapDao.persist(grMap); - } - } - } - }); - - invalidateIAMCache(); - return group; - } - - @DB - @Override - public IAMGroup removeAccountsFromGroup(final List acctIds, final Long groupId) { - // get the Acl Group entity - IAMGroup group = _aclGroupDao.findById(groupId); - if (group == null) { - throw new InvalidParameterValueException("Unable to find acl group: " + groupId - + "; failed to remove accounts from acl group."); - } - - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - // remove entries from acl_group_account_map table - for (Long acctId : acctIds) { - IAMGroupAccountMapVO grMap = _aclGroupAccountMapDao.findByGroupAndAccount(groupId, acctId); - if (grMap != null) { - // not removed yet - _aclGroupAccountMapDao.remove(grMap.getId()); - } - } - } - }); - - invalidateIAMCache(); - return group; - } - - @Override - public List listAccountsByGroup(long groupId) { - List grpAcctMap = _aclGroupAccountMapDao.listByGroupId(groupId); - if (grpAcctMap == null || grpAcctMap.size() == 0) { - return new ArrayList(); - } - - List accts = new ArrayList(); - for (IAMGroupAccountMapVO grpAcct : grpAcctMap) { - accts.add(grpAcct.getAccountId()); - } - return accts; - } - - @Override - public Pair, Integer> listIAMGroups(Long iamGroupId, String iamGroupName, String path, Long startIndex, Long pageSize) { - if (iamGroupId != null) { - IAMGroup group = _aclGroupDao.findById(iamGroupId); - if (group == null) { - throw new InvalidParameterValueException("Unable to find acl group by id " + iamGroupId); - } - } - - Filter searchFilter = new Filter(IAMGroupVO.class, "id", true, startIndex, pageSize); - - SearchBuilder sb = _aclGroupDao.createSearchBuilder(); - sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); - sb.and("path", sb.entity().getPath(), SearchCriteria.Op.LIKE); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - - SearchCriteria sc = sb.create(); - - if (iamGroupName != null) { - sc.setParameters("name", iamGroupName); - } - - if (iamGroupId != null) { - sc.setParameters("id", iamGroupId); - } - - sc.setParameters("path", path + "%"); - - Pair, Integer> groups = _aclGroupDao.searchAndCount(sc, searchFilter); - return new Pair, Integer>(new ArrayList(groups.first()), groups.second()); - } - - @Override - public List listParentIAMGroups(long groupId) { - IAMGroup group = _aclGroupDao.findById(groupId); - if (group == null) { - throw new InvalidParameterValueException("Unable to find acl group by id " + groupId); - } - - String path = group.getPath(); - List pathList = new ArrayList(); - - String[] parts = path.split("/"); - - for (String part : parts) { - int start = path.indexOf(part); - if (start > 0) { - String subPath = path.substring(0, start); - pathList.add(subPath); - } - } - - if (pathList.isEmpty()) { - return new ArrayList(); - } - - SearchBuilder sb = _aclGroupDao.createSearchBuilder(); - sb.and("paths", sb.entity().getPath(), SearchCriteria.Op.IN); - - SearchCriteria sc = sb.create(); - sc.setParameters("paths", pathList.toArray()); - - List groups = _aclGroupDao.search(sc, null); - - return new ArrayList(groups); - - } - - @DB - @Override - public IAMPolicy createIAMPolicy(final String iamPolicyName, final String description, final Long parentPolicyId, final String path) { - - // check if the policy is already existing - IAMPolicy ro = _aclPolicyDao.findByName(iamPolicyName); - if (ro != null) { - throw new InvalidParameterValueException( - "Unable to create acl policy with name " + iamPolicyName - + " already exisits"); - } - - IAMPolicy role = Transaction.execute(new TransactionCallback() { - @Override - public IAMPolicy doInTransaction(TransactionStatus status) { - IAMPolicyVO rvo = new IAMPolicyVO(iamPolicyName, description); - rvo.setPath(path); - - IAMPolicy role = _aclPolicyDao.persist(rvo); - if (parentPolicyId != null) { - // copy parent role permissions - List perms = _policyPermissionDao.listByPolicy(parentPolicyId); - if (perms != null) { - for (IAMPolicyPermissionVO perm : perms) { - perm.setAclPolicyId(role.getId()); - _policyPermissionDao.persist(perm); - } - } - } - return role; - } - }); - - - return role; - } - - @DB - @Override - public boolean deleteIAMPolicy(final long iamPolicyId) { - // get the Acl Policy entity - final IAMPolicy policy = _aclPolicyDao.findById(iamPolicyId); - if (policy == null) { - throw new InvalidParameterValueException("Unable to find acl policy: " + iamPolicyId - + "; failed to delete acl policy."); - } - - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - // remove this policy related entry in acl_group_policy_map - List groupPolicyMap = _aclGroupPolicyMapDao.listByPolicyId(policy.getId()); - if (groupPolicyMap != null) { - for (IAMGroupPolicyMapVO gr : groupPolicyMap) { - _aclGroupPolicyMapDao.remove(gr.getId()); - } - } - - // remove this policy related entry in acl_account_policy_map table - List policyAcctMap = _aclAccountPolicyMapDao.listByPolicyId(policy.getId()); - if (policyAcctMap != null) { - for (IAMAccountPolicyMapVO policyAcct : policyAcctMap) { - _aclAccountPolicyMapDao.remove(policyAcct.getId()); - } - } - - // remove this policy related entry in acl_policy_permission table - List policyPermMap = _policyPermissionDao.listByPolicy(policy.getId()); - if (policyPermMap != null) { - for (IAMPolicyPermissionVO policyPerm : policyPermMap) { - _policyPermissionDao.remove(policyPerm.getId()); - } - } - - // remove this role from acl_role table - _aclPolicyDao.remove(iamPolicyId); - } - }); - - invalidateIAMCache(); - - return true; - } - - - @SuppressWarnings("unchecked") - @Override - public List listIAMPolicies(long accountId) { - - // static policies of the account - SearchBuilder groupSB = _aclGroupAccountMapDao.createSearchBuilder(); - groupSB.and("account", groupSB.entity().getAccountId(), Op.EQ); - - GenericSearchBuilder policySB = _aclGroupPolicyMapDao.createSearchBuilder(Long.class); - policySB.selectFields(policySB.entity().getAclPolicyId()); - policySB.join("accountgroupjoin", groupSB, groupSB.entity().getAclGroupId(), policySB.entity().getAclGroupId(), - JoinType.INNER); - policySB.done(); - SearchCriteria policySc = policySB.create(); - policySc.setJoinParameters("accountgroupjoin", "account", accountId); - - List policyIds = _aclGroupPolicyMapDao.customSearch(policySc, null); - // add policies directly attached to the account - List acctPolicies = _aclAccountPolicyMapDao.listByAccountId(accountId); - for (IAMAccountPolicyMapVO p : acctPolicies) { - policyIds.add(p.getIamPolicyId()); - } - if (policyIds.size() == 0) { - return new ArrayList(); - } - SearchBuilder sb = _aclPolicyDao.createSearchBuilder(); - sb.and("ids", sb.entity().getId(), Op.IN); - SearchCriteria sc = sb.create(); - sc.setParameters("ids", policyIds.toArray(new Object[policyIds.size()])); - @SuppressWarnings("rawtypes") - List policies = _aclPolicyDao.customSearch(sc, null); - - return policies; - - } - - @SuppressWarnings("unchecked") - @Override - public List listIAMPoliciesByGroup(long groupId) { - List policyGrpMap = _aclGroupPolicyMapDao.listByGroupId(groupId); - if (policyGrpMap == null || policyGrpMap.size() == 0) { - return new ArrayList(); - } - - List policyIds = new ArrayList(); - for (IAMGroupPolicyMapVO pg : policyGrpMap) { - policyIds.add(pg.getAclPolicyId()); - } - - SearchBuilder sb = _aclPolicyDao.createSearchBuilder(); - sb.and("ids", sb.entity().getId(), Op.IN); - SearchCriteria sc = sb.create(); - sc.setParameters("ids", policyIds.toArray(new Object[policyIds.size()])); - @SuppressWarnings("rawtypes") - List policies = _aclPolicyDao.customSearch(sc, null); - - return policies; - } - - @SuppressWarnings("unchecked") - @Override - public List listRecursiveIAMPoliciesByGroup(long groupId) { - List policyGrpMap = _aclGroupPolicyMapDao.listByGroupId(groupId); - if (policyGrpMap == null || policyGrpMap.size() == 0) { - return new ArrayList(); - } - - List policyIds = new ArrayList(); - for (IAMGroupPolicyMapVO pg : policyGrpMap) { - policyIds.add(pg.getAclPolicyId()); - } - - SearchBuilder permSb = _policyPermissionDao.createSearchBuilder(); - permSb.and("isRecursive", permSb.entity().isRecursive(), Op.EQ); - - SearchBuilder sb = _aclPolicyDao.createSearchBuilder(); - sb.and("ids", sb.entity().getId(), Op.IN); - sb.join("recursivePerm", permSb, sb.entity().getId(), permSb.entity().getAclPolicyId(), - JoinBuilder.JoinType.INNER); - - SearchCriteria sc = sb.create(); - sc.setParameters("ids", policyIds.toArray(new Object[policyIds.size()])); - sc.setJoinParameters("recursivePerm", "isRecursive", true); - - @SuppressWarnings("rawtypes") - List policies = _aclPolicyDao.customSearch(sc, null); - - return policies; - } - - - @SuppressWarnings("unchecked") - @Override - public Pair, Integer> listIAMPolicies(Long iamPolicyId, String iamPolicyName, String path, Long startIndex, Long pageSize) { - - if (iamPolicyId != null) { - IAMPolicy policy = _aclPolicyDao.findById(iamPolicyId); - if (policy == null) { - throw new InvalidParameterValueException("Unable to find acl policy by id " + iamPolicyId); - } - } - - Filter searchFilter = new Filter(IAMPolicyVO.class, "id", true, startIndex, pageSize); - - SearchBuilder sb = _aclPolicyDao.createSearchBuilder(); - sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); - sb.and("path", sb.entity().getPath(), SearchCriteria.Op.LIKE); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - - SearchCriteria sc = sb.create(); - - if (iamPolicyName != null) { - sc.setParameters("name", iamPolicyName); - } - - if (iamPolicyId != null) { - sc.setParameters("id", iamPolicyId); - } - - sc.setParameters("path", path + "%"); - - Pair, Integer> policies = _aclPolicyDao.searchAndCount(sc, searchFilter); - @SuppressWarnings("rawtypes") - List policyList = policies.first(); - return new Pair, Integer>(policyList, policies.second()); - } - - @DB - @Override - public IAMGroup attachIAMPoliciesToGroup(final List policyIds, final Long groupId) { - // get the Acl Group entity - IAMGroup group = _aclGroupDao.findById(groupId); - if (group == null) { - throw new InvalidParameterValueException("Unable to find acl group: " + groupId - + "; failed to add roles to acl group."); - } - - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - // add entries in acl_group_policy_map table - for (Long policyId : policyIds) { - IAMPolicy policy = _aclPolicyDao.findById(policyId); - if (policy == null) { - throw new InvalidParameterValueException("Unable to find acl policy: " + policyId - + "; failed to add policies to acl group."); - } - - IAMGroupPolicyMapVO grMap = _aclGroupPolicyMapDao.findByGroupAndPolicy(groupId, policyId); - if (grMap == null) { - // not there already - grMap = new IAMGroupPolicyMapVO(groupId, policyId); - _aclGroupPolicyMapDao.persist(grMap); - } - } - } - }); - - invalidateIAMCache(); - return group; - } - - @DB - @Override - public IAMGroup removeIAMPoliciesFromGroup(final List policyIds, final Long groupId) { - // get the Acl Group entity - IAMGroup group = _aclGroupDao.findById(groupId); - if (group == null) { - throw new InvalidParameterValueException("Unable to find acl group: " + groupId - + "; failed to remove roles from acl group."); - } - - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - // add entries in acl_group_role_map table - for (Long policyId : policyIds) { - IAMPolicy policy = _aclPolicyDao.findById(policyId); - if (policy == null) { - throw new InvalidParameterValueException("Unable to find acl policy: " + policyId - + "; failed to add policies to acl group."); - } - - IAMGroupPolicyMapVO grMap = _aclGroupPolicyMapDao.findByGroupAndPolicy(groupId, policyId); - if (grMap != null) { - // not removed yet - _aclGroupPolicyMapDao.remove(grMap.getId()); - } - } - } - }); - - invalidateIAMCache(); - return group; - } - - - @Override - public void attachIAMPolicyToAccounts(final Long policyId, final List acctIds) { - IAMPolicy policy = _aclPolicyDao.findById(policyId); - if (policy == null) { - throw new InvalidParameterValueException("Unable to find acl policy: " + policyId - + "; failed to add policy to account."); - } - - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - // add entries in acl_group_policy_map table - for (Long acctId : acctIds) { - IAMAccountPolicyMapVO acctMap = _aclAccountPolicyMapDao.findByAccountAndPolicy(acctId, policyId); - if (acctMap == null) { - // not there already - acctMap = new IAMAccountPolicyMapVO(acctId, policyId); - _aclAccountPolicyMapDao.persist(acctMap); - } - } - } - }); - - invalidateIAMCache(); - } - - @Override - public void removeIAMPolicyFromAccounts(final Long policyId, final List acctIds) { - IAMPolicy policy = _aclPolicyDao.findById(policyId); - if (policy == null) { - throw new InvalidParameterValueException("Unable to find acl policy: " + policyId - + "; failed to add policy to account."); - } - - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - // add entries in acl_group_policy_map table - for (Long acctId : acctIds) { - IAMAccountPolicyMapVO acctMap = _aclAccountPolicyMapDao.findByAccountAndPolicy(acctId, policyId); - if (acctMap != null) { - // exists - _aclAccountPolicyMapDao.remove(acctMap.getId()); - } - } - } - }); - - invalidateIAMCache(); - } - - @DB - @Override - public IAMPolicy addIAMPermissionToIAMPolicy(long iamPolicyId, String entityType, String scope, Long scopeId, - String action, String accessType, Permission perm, Boolean recursive) { - // get the Acl Policy entity - IAMPolicy policy = _aclPolicyDao.findById(iamPolicyId); - if (policy == null) { - throw new InvalidParameterValueException("Unable to find acl policy: " + iamPolicyId - + "; failed to add permission to policy."); - } - - // add entry in acl_policy_permission table - IAMPolicyPermissionVO permit = _policyPermissionDao.findByPolicyAndEntity(iamPolicyId, entityType, scope, scopeId, action, perm); - if (permit == null) { - // not there already - permit = new IAMPolicyPermissionVO(iamPolicyId, action, entityType, accessType, scope, scopeId, perm, - recursive); - _policyPermissionDao.persist(permit); - } - - invalidateIAMCache(); - return policy; - - } - - @DB - @Override - public IAMPolicy removeIAMPermissionFromIAMPolicy(long iamPolicyId, String entityType, String scope, Long scopeId, - String action) { - // get the Acl Policy entity - IAMPolicy policy = _aclPolicyDao.findById(iamPolicyId); - if (policy == null) { - throw new InvalidParameterValueException("Unable to find acl policy: " + iamPolicyId - + "; failed to revoke permission from policy."); - } - // remove entry from acl_entity_permission table - IAMPolicyPermissionVO permit = _policyPermissionDao.findByPolicyAndEntity(iamPolicyId, entityType, scope, scopeId, action, Permission.Allow); - if (permit != null) { - // not removed yet - _policyPermissionDao.remove(permit.getId()); - } - - invalidateIAMCache(); - return policy; - } - - @DB - @Override - public void removeIAMPermissionForEntity(final String entityType, final Long entityId) { - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - // remove entry from acl_entity_permission table - List permitList = _policyPermissionDao.listByEntity(entityType, entityId); - for (IAMPolicyPermissionVO permit : permitList) { - long policyId = permit.getAclPolicyId(); - _policyPermissionDao.remove(permit.getId()); - - // remove the policy if there are no other permissions - if ((_policyPermissionDao.listByPolicy(policyId)).isEmpty()) { - deleteIAMPolicy(policyId); - } - } - } - }); - - invalidateIAMCache(); - } - - @DB - @Override - public IAMPolicy resetIAMPolicy(long iamPolicyId) { - // get the Acl Policy entity - IAMPolicy policy = _aclPolicyDao.findById(iamPolicyId); - if (policy == null) { - throw new InvalidParameterValueException("Unable to find acl policy: " + iamPolicyId - + "; failed to reset the policy."); - } - - SearchBuilder sb = _policyPermissionDao.createSearchBuilder(); - sb.and("policyId", sb.entity().getAclPolicyId(), SearchCriteria.Op.EQ); - sb.and("scope", sb.entity().getScope(), SearchCriteria.Op.EQ); - sb.done(); - SearchCriteria permissionSC = sb.create(); - permissionSC.setParameters("policyId", iamPolicyId); - _policyPermissionDao.expunge(permissionSC); - - invalidateIAMCache(); - return policy; - } - - @Override - public boolean isActionAllowedForPolicies(String action, List policies) { - - boolean allowed = false; - - if (policies == null || policies.size() == 0) { - return allowed; - } - - List policyIds = new ArrayList(); - for (IAMPolicy policy : policies) { - policyIds.add(policy.getId()); - } - - SearchBuilder sb = _policyPermissionDao.createSearchBuilder(); - sb.and("action", sb.entity().getAction(), Op.EQ); - sb.and("policyId", sb.entity().getAclPolicyId(), Op.IN); - - SearchCriteria sc = sb.create(); - sc.setParameters("policyId", policyIds.toArray(new Object[policyIds.size()])); - sc.setParameters("action", action); - - List permissions = _policyPermissionDao.customSearch(sc, null); - - if (permissions != null && !permissions.isEmpty()) { - allowed = true; - } - - return allowed; - } - - - @Override - public List getGrantedEntities(long accountId, String action, String scope) { - // Get the static Policies of the Caller - List policies = listIAMPolicies(accountId); - // for each policy, find granted permission within the given scope - List entityIds = new ArrayList(); - for (IAMPolicy policy : policies) { - List pp = _policyPermissionDao.listByPolicyActionAndScope(policy.getId(), action, - scope, null); - if (pp != null) { - for (IAMPolicyPermissionVO p : pp) { - if (p.getScopeId() != null) { - entityIds.add(p.getScopeId()); - } - } - } - } - return entityIds; - } - - @Override - @SuppressWarnings("unchecked") - public List listPolicyPermissions(long policyId) { - @SuppressWarnings("rawtypes") - List pp = _policyPermissionDao.listByPolicy(policyId); - return pp; - } - - @SuppressWarnings("unchecked") - @Override - public List listPolicyPermissionsByScope(long policyId, String action, String scope, AccessType accessType) { - @SuppressWarnings("rawtypes") - List pp = _policyPermissionDao.listByPolicyActionAndScope(policyId, action, scope, accessType.toString()); - return pp; - } - - @SuppressWarnings("unchecked") - @Override - public List listPolicyPermissionByActionAndEntity(long policyId, String action, - String entityType) { - @SuppressWarnings("rawtypes") - List pp = _policyPermissionDao.listByPolicyActionAndEntity(policyId, action, entityType); - return pp; - } - - @SuppressWarnings("unchecked") - @Override - public List listPolicyPermissionByAccessAndEntity(long policyId, String accessType, - String entityType) { - @SuppressWarnings("rawtypes") - List pp = _policyPermissionDao.listByPolicyAccessAndEntity(policyId, accessType, entityType); - return pp; - } - - @Override - public IAMPolicy getResourceOwnerPolicy() { - return _aclPolicyDao.findByName("RESOURCE_OWNER"); - } - - // search for policy with only one resource grant permission - @Override - public IAMPolicy getResourceGrantPolicy(String entityType, Long entityId, String accessType, String action) { - List policyList = _aclPolicyDao.listAll(); - for (IAMPolicyVO policy : policyList){ - List pp = listPolicyPermissions(policy.getId()); - if ( pp != null && pp.size() == 1){ - // resource grant policy should only have one ACL permission assigned - IAMPolicyPermission permit = pp.get(0); - if ( permit.getEntityType().equals(entityType) && permit.getScope().equals(PermissionScope.RESOURCE.toString()) && permit.getScopeId().longValue() == entityId.longValue()){ - if (accessType != null && permit.getAccessType().equals(accessType)){ - return policy; - } else if (action != null && permit.getAction().equals(action)) { - return policy; - } - } - } - } - return null; - } - -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.iam.server; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.inject.Inject; +import javax.naming.ConfigurationException; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.acl.PermissionScope; +import org.apache.cloudstack.iam.api.IAMGroup; +import org.apache.cloudstack.iam.api.IAMPolicy; +import org.apache.cloudstack.iam.api.IAMPolicyPermission; +import org.apache.cloudstack.iam.api.IAMPolicyPermission.Permission; +import org.apache.cloudstack.iam.api.IAMService; +import org.apache.cloudstack.iam.server.dao.IAMAccountPolicyMapDao; +import org.apache.cloudstack.iam.server.dao.IAMGroupAccountMapDao; +import org.apache.cloudstack.iam.server.dao.IAMGroupDao; +import org.apache.cloudstack.iam.server.dao.IAMGroupPolicyMapDao; +import org.apache.cloudstack.iam.server.dao.IAMPolicyDao; +import org.apache.cloudstack.iam.server.dao.IAMPolicyPermissionDao; + +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.Pair; +import com.cloud.utils.component.Manager; +import com.cloud.utils.component.ManagerBase; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.EntityManager; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.JoinBuilder; +import com.cloud.utils.db.JoinBuilder.JoinType; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallback; +import com.cloud.utils.db.TransactionCallbackNoReturn; +import com.cloud.utils.db.TransactionStatus; + +@Local(value = {IAMService.class}) +public class IAMServiceImpl extends ManagerBase implements IAMService, Manager { + + public static final Logger s_logger = Logger.getLogger(IAMServiceImpl.class); + private String _name; + + @Inject + IAMPolicyDao _aclPolicyDao; + + @Inject + IAMGroupDao _aclGroupDao; + + @Inject + EntityManager _entityMgr; + + @Inject + IAMGroupPolicyMapDao _aclGroupPolicyMapDao; + + @Inject + IAMAccountPolicyMapDao _aclAccountPolicyMapDao; + + @Inject + IAMGroupAccountMapDao _aclGroupAccountMapDao; + + @Inject + IAMPolicyPermissionDao _policyPermissionDao; + + private Cache _iamCache; + + private void createIAMCache(final Map params) { + final String value = (String)params.get("cache.size"); + + if (value != null) { + final CacheManager cm = CacheManager.create(); + final int maxElements = NumbersUtil.parseInt(value, 0); + final int live = NumbersUtil.parseInt((String)params.get("cache.time.to.live"), 300); + final int idle = NumbersUtil.parseInt((String)params.get("cache.time.to.idle"), 300); + _iamCache = new Cache(getName(), maxElements, false, live == -1, live == -1 ? Integer.MAX_VALUE : live, idle); + cm.addCache(_iamCache); + s_logger.info("IAM Cache created: " + _iamCache.toString()); + } else { + _iamCache = null; + } + } + + @Override + public void addToIAMCache(Object accessKey, Object allowDeny) { + if (_iamCache != null) { + try { + s_logger.debug("Put IAM access check for " + accessKey + " in cache"); + _iamCache.put(new Element(accessKey, allowDeny)); + } catch (final Exception e) { + s_logger.debug("Can't put " + accessKey + " to IAM cache", e); + } + } + } + + @Override + public void invalidateIAMCache() { + //This may need to use event bus to publish to other MS, but event bus now is missing this functionality to handle PublishScope.GLOBAL + if (_iamCache != null) { + s_logger.debug("Invalidate IAM cache"); + _iamCache.removeAll(); + } + } + + @Override + public Object getFromIAMCache(Object accessKey) { + if (_iamCache != null) { + final Element element = _iamCache.get(accessKey); + return element == null ? null : element.getObjectValue(); + } + return null; + } + + @Override + public boolean configure(final String name, final Map params) throws ConfigurationException { + boolean result = super.configure(name, params); + // create IAM cache + createIAMCache(params); + return result; + } + + @DB + @Override + public IAMGroup createIAMGroup(String iamGroupName, String description, String path) { + // check if the group is already existing + IAMGroup grp = _aclGroupDao.findByName(path, iamGroupName); + if (grp != null) { + throw new InvalidParameterValueException( + "Unable to create acl group with name " + iamGroupName + + " already exisits for path " + path); + } + IAMGroupVO rvo = new IAMGroupVO(iamGroupName, description); + rvo.setPath(path); + + return _aclGroupDao.persist(rvo); + } + + @DB + @Override + public boolean deleteIAMGroup(final Long iamGroupId) { + // get the Acl Group entity + final IAMGroup grp = _aclGroupDao.findById(iamGroupId); + if (grp == null) { + throw new InvalidParameterValueException("Unable to find acl group: " + iamGroupId + + "; failed to delete acl group."); + } + + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + // remove this group related entry in acl_group_policy_map + List groupPolicyMap = _aclGroupPolicyMapDao.listByGroupId(grp.getId()); + if (groupPolicyMap != null) { + for (IAMGroupPolicyMapVO gr : groupPolicyMap) { + _aclGroupPolicyMapDao.remove(gr.getId()); + } + } + + // remove this group related entry in acl_group_account table + List groupAcctMap = _aclGroupAccountMapDao.listByGroupId(grp.getId()); + if (groupAcctMap != null) { + for (IAMGroupAccountMapVO grpAcct : groupAcctMap) { + _aclGroupAccountMapDao.remove(grpAcct.getId()); + } + } + + // remove this group from acl_group table + _aclGroupDao.remove(iamGroupId); + } + }); + + invalidateIAMCache(); + return true; + } + + @SuppressWarnings("unchecked") + @Override + public List listIAMGroups(long accountId) { + + GenericSearchBuilder groupSB = _aclGroupAccountMapDao.createSearchBuilder(Long.class); + groupSB.selectFields(groupSB.entity().getAclGroupId()); + groupSB.and("account", groupSB.entity().getAccountId(), Op.EQ); + SearchCriteria groupSc = groupSB.create(); + groupSc.setParameters("account", accountId); + + List groupIds = _aclGroupAccountMapDao.customSearch(groupSc, null); + + if (groupIds == null || groupIds.isEmpty()) { + return new ArrayList(); + } + SearchBuilder sb = _aclGroupDao.createSearchBuilder(); + sb.and("ids", sb.entity().getId(), Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("ids", groupIds.toArray(new Object[groupIds.size()])); + @SuppressWarnings("rawtypes") + List groups = _aclGroupDao.search(sc, null); + return groups; + } + + @DB + @Override + public IAMGroup addAccountsToGroup(final List acctIds, final Long groupId) { + // get the Acl Group entity + IAMGroup group = _aclGroupDao.findById(groupId); + if (group == null) { + throw new InvalidParameterValueException("Unable to find acl group: " + groupId + + "; failed to add accounts to acl group."); + } + + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + // add entries in acl_group_account_map table + for (Long acctId : acctIds) { + // check account permissions + IAMGroupAccountMapVO grMap = _aclGroupAccountMapDao.findByGroupAndAccount(groupId, acctId); + if (grMap == null) { + // not there already + grMap = new IAMGroupAccountMapVO(groupId, acctId); + _aclGroupAccountMapDao.persist(grMap); + } + } + } + }); + + invalidateIAMCache(); + return group; + } + + @DB + @Override + public IAMGroup removeAccountsFromGroup(final List acctIds, final Long groupId) { + // get the Acl Group entity + IAMGroup group = _aclGroupDao.findById(groupId); + if (group == null) { + throw new InvalidParameterValueException("Unable to find acl group: " + groupId + + "; failed to remove accounts from acl group."); + } + + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + // remove entries from acl_group_account_map table + for (Long acctId : acctIds) { + IAMGroupAccountMapVO grMap = _aclGroupAccountMapDao.findByGroupAndAccount(groupId, acctId); + if (grMap != null) { + // not removed yet + _aclGroupAccountMapDao.remove(grMap.getId()); + } + } + } + }); + + invalidateIAMCache(); + return group; + } + + @Override + public List listAccountsByGroup(long groupId) { + List grpAcctMap = _aclGroupAccountMapDao.listByGroupId(groupId); + if (grpAcctMap == null || grpAcctMap.size() == 0) { + return new ArrayList(); + } + + List accts = new ArrayList(); + for (IAMGroupAccountMapVO grpAcct : grpAcctMap) { + accts.add(grpAcct.getAccountId()); + } + return accts; + } + + @Override + public Pair, Integer> listIAMGroups(Long iamGroupId, String iamGroupName, String path, Long startIndex, Long pageSize) { + if (iamGroupId != null) { + IAMGroup group = _aclGroupDao.findById(iamGroupId); + if (group == null) { + throw new InvalidParameterValueException("Unable to find acl group by id " + iamGroupId); + } + } + + Filter searchFilter = new Filter(IAMGroupVO.class, "id", true, startIndex, pageSize); + + SearchBuilder sb = _aclGroupDao.createSearchBuilder(); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); + sb.and("path", sb.entity().getPath(), SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + + SearchCriteria sc = sb.create(); + + if (iamGroupName != null) { + sc.setParameters("name", iamGroupName); + } + + if (iamGroupId != null) { + sc.setParameters("id", iamGroupId); + } + + sc.setParameters("path", path + "%"); + + Pair, Integer> groups = _aclGroupDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(new ArrayList(groups.first()), groups.second()); + } + + @Override + public List listParentIAMGroups(long groupId) { + IAMGroup group = _aclGroupDao.findById(groupId); + if (group == null) { + throw new InvalidParameterValueException("Unable to find acl group by id " + groupId); + } + + String path = group.getPath(); + List pathList = new ArrayList(); + + String[] parts = path.split("/"); + + for (String part : parts) { + int start = path.indexOf(part); + if (start > 0) { + String subPath = path.substring(0, start); + pathList.add(subPath); + } + } + + if (pathList.isEmpty()) { + return new ArrayList(); + } + + SearchBuilder sb = _aclGroupDao.createSearchBuilder(); + sb.and("paths", sb.entity().getPath(), SearchCriteria.Op.IN); + + SearchCriteria sc = sb.create(); + sc.setParameters("paths", pathList.toArray()); + + List groups = _aclGroupDao.search(sc, null); + + return new ArrayList(groups); + + } + + @DB + @Override + public IAMPolicy createIAMPolicy(final String iamPolicyName, final String description, final Long parentPolicyId, final String path) { + + // check if the policy is already existing + IAMPolicy ro = _aclPolicyDao.findByName(iamPolicyName); + if (ro != null) { + throw new InvalidParameterValueException( + "Unable to create acl policy with name " + iamPolicyName + + " already exisits"); + } + + IAMPolicy role = Transaction.execute(new TransactionCallback() { + @Override + public IAMPolicy doInTransaction(TransactionStatus status) { + IAMPolicyVO rvo = new IAMPolicyVO(iamPolicyName, description); + rvo.setPath(path); + + IAMPolicy role = _aclPolicyDao.persist(rvo); + if (parentPolicyId != null) { + // copy parent role permissions + List perms = _policyPermissionDao.listByPolicy(parentPolicyId); + if (perms != null) { + for (IAMPolicyPermissionVO perm : perms) { + perm.setAclPolicyId(role.getId()); + _policyPermissionDao.persist(perm); + } + } + } + return role; + } + }); + + + return role; + } + + @DB + @Override + public boolean deleteIAMPolicy(final long iamPolicyId) { + // get the Acl Policy entity + final IAMPolicy policy = _aclPolicyDao.findById(iamPolicyId); + if (policy == null) { + throw new InvalidParameterValueException("Unable to find acl policy: " + iamPolicyId + + "; failed to delete acl policy."); + } + + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + // remove this policy related entry in acl_group_policy_map + List groupPolicyMap = _aclGroupPolicyMapDao.listByPolicyId(policy.getId()); + if (groupPolicyMap != null) { + for (IAMGroupPolicyMapVO gr : groupPolicyMap) { + _aclGroupPolicyMapDao.remove(gr.getId()); + } + } + + // remove this policy related entry in acl_account_policy_map table + List policyAcctMap = _aclAccountPolicyMapDao.listByPolicyId(policy.getId()); + if (policyAcctMap != null) { + for (IAMAccountPolicyMapVO policyAcct : policyAcctMap) { + _aclAccountPolicyMapDao.remove(policyAcct.getId()); + } + } + + // remove this policy related entry in acl_policy_permission table + List policyPermMap = _policyPermissionDao.listByPolicy(policy.getId()); + if (policyPermMap != null) { + for (IAMPolicyPermissionVO policyPerm : policyPermMap) { + _policyPermissionDao.remove(policyPerm.getId()); + } + } + + // remove this role from acl_role table + _aclPolicyDao.remove(iamPolicyId); + } + }); + + invalidateIAMCache(); + + return true; + } + + + @SuppressWarnings("unchecked") + @Override + public List listIAMPolicies(long accountId) { + + // static policies of the account + SearchBuilder groupSB = _aclGroupAccountMapDao.createSearchBuilder(); + groupSB.and("account", groupSB.entity().getAccountId(), Op.EQ); + + GenericSearchBuilder policySB = _aclGroupPolicyMapDao.createSearchBuilder(Long.class); + policySB.selectFields(policySB.entity().getAclPolicyId()); + policySB.join("accountgroupjoin", groupSB, groupSB.entity().getAclGroupId(), policySB.entity().getAclGroupId(), + JoinType.INNER); + policySB.done(); + SearchCriteria policySc = policySB.create(); + policySc.setJoinParameters("accountgroupjoin", "account", accountId); + + List policyIds = _aclGroupPolicyMapDao.customSearch(policySc, null); + // add policies directly attached to the account + List acctPolicies = _aclAccountPolicyMapDao.listByAccountId(accountId); + for (IAMAccountPolicyMapVO p : acctPolicies) { + policyIds.add(p.getIamPolicyId()); + } + if (policyIds.size() == 0) { + return new ArrayList(); + } + SearchBuilder sb = _aclPolicyDao.createSearchBuilder(); + sb.and("ids", sb.entity().getId(), Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("ids", policyIds.toArray(new Object[policyIds.size()])); + @SuppressWarnings("rawtypes") + List policies = _aclPolicyDao.customSearch(sc, null); + + return policies; + + } + + @SuppressWarnings("unchecked") + @Override + public List listIAMPoliciesByGroup(long groupId) { + List policyGrpMap = _aclGroupPolicyMapDao.listByGroupId(groupId); + if (policyGrpMap == null || policyGrpMap.size() == 0) { + return new ArrayList(); + } + + List policyIds = new ArrayList(); + for (IAMGroupPolicyMapVO pg : policyGrpMap) { + policyIds.add(pg.getAclPolicyId()); + } + + SearchBuilder sb = _aclPolicyDao.createSearchBuilder(); + sb.and("ids", sb.entity().getId(), Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("ids", policyIds.toArray(new Object[policyIds.size()])); + @SuppressWarnings("rawtypes") + List policies = _aclPolicyDao.customSearch(sc, null); + + return policies; + } + + @SuppressWarnings("unchecked") + @Override + public List listRecursiveIAMPoliciesByGroup(long groupId) { + List policyGrpMap = _aclGroupPolicyMapDao.listByGroupId(groupId); + if (policyGrpMap == null || policyGrpMap.size() == 0) { + return new ArrayList(); + } + + List policyIds = new ArrayList(); + for (IAMGroupPolicyMapVO pg : policyGrpMap) { + policyIds.add(pg.getAclPolicyId()); + } + + SearchBuilder permSb = _policyPermissionDao.createSearchBuilder(); + permSb.and("isRecursive", permSb.entity().isRecursive(), Op.EQ); + + SearchBuilder sb = _aclPolicyDao.createSearchBuilder(); + sb.and("ids", sb.entity().getId(), Op.IN); + sb.join("recursivePerm", permSb, sb.entity().getId(), permSb.entity().getAclPolicyId(), + JoinBuilder.JoinType.INNER); + + SearchCriteria sc = sb.create(); + sc.setParameters("ids", policyIds.toArray(new Object[policyIds.size()])); + sc.setJoinParameters("recursivePerm", "isRecursive", true); + + @SuppressWarnings("rawtypes") + List policies = _aclPolicyDao.customSearch(sc, null); + + return policies; + } + + + @SuppressWarnings("unchecked") + @Override + public Pair, Integer> listIAMPolicies(Long iamPolicyId, String iamPolicyName, String path, Long startIndex, Long pageSize) { + + if (iamPolicyId != null) { + IAMPolicy policy = _aclPolicyDao.findById(iamPolicyId); + if (policy == null) { + throw new InvalidParameterValueException("Unable to find acl policy by id " + iamPolicyId); + } + } + + Filter searchFilter = new Filter(IAMPolicyVO.class, "id", true, startIndex, pageSize); + + SearchBuilder sb = _aclPolicyDao.createSearchBuilder(); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); + sb.and("path", sb.entity().getPath(), SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + + SearchCriteria sc = sb.create(); + + if (iamPolicyName != null) { + sc.setParameters("name", iamPolicyName); + } + + if (iamPolicyId != null) { + sc.setParameters("id", iamPolicyId); + } + + sc.setParameters("path", path + "%"); + + Pair, Integer> policies = _aclPolicyDao.searchAndCount(sc, searchFilter); + @SuppressWarnings("rawtypes") + List policyList = policies.first(); + return new Pair, Integer>(policyList, policies.second()); + } + + @DB + @Override + public IAMGroup attachIAMPoliciesToGroup(final List policyIds, final Long groupId) { + // get the Acl Group entity + IAMGroup group = _aclGroupDao.findById(groupId); + if (group == null) { + throw new InvalidParameterValueException("Unable to find acl group: " + groupId + + "; failed to add roles to acl group."); + } + + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + // add entries in acl_group_policy_map table + for (Long policyId : policyIds) { + IAMPolicy policy = _aclPolicyDao.findById(policyId); + if (policy == null) { + throw new InvalidParameterValueException("Unable to find acl policy: " + policyId + + "; failed to add policies to acl group."); + } + + IAMGroupPolicyMapVO grMap = _aclGroupPolicyMapDao.findByGroupAndPolicy(groupId, policyId); + if (grMap == null) { + // not there already + grMap = new IAMGroupPolicyMapVO(groupId, policyId); + _aclGroupPolicyMapDao.persist(grMap); + } + } + } + }); + + invalidateIAMCache(); + return group; + } + + @DB + @Override + public IAMGroup removeIAMPoliciesFromGroup(final List policyIds, final Long groupId) { + // get the Acl Group entity + IAMGroup group = _aclGroupDao.findById(groupId); + if (group == null) { + throw new InvalidParameterValueException("Unable to find acl group: " + groupId + + "; failed to remove roles from acl group."); + } + + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + // add entries in acl_group_role_map table + for (Long policyId : policyIds) { + IAMPolicy policy = _aclPolicyDao.findById(policyId); + if (policy == null) { + throw new InvalidParameterValueException("Unable to find acl policy: " + policyId + + "; failed to add policies to acl group."); + } + + IAMGroupPolicyMapVO grMap = _aclGroupPolicyMapDao.findByGroupAndPolicy(groupId, policyId); + if (grMap != null) { + // not removed yet + _aclGroupPolicyMapDao.remove(grMap.getId()); + } + } + } + }); + + invalidateIAMCache(); + return group; + } + + + @Override + public void attachIAMPolicyToAccounts(final Long policyId, final List acctIds) { + IAMPolicy policy = _aclPolicyDao.findById(policyId); + if (policy == null) { + throw new InvalidParameterValueException("Unable to find acl policy: " + policyId + + "; failed to add policy to account."); + } + + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + // add entries in acl_group_policy_map table + for (Long acctId : acctIds) { + IAMAccountPolicyMapVO acctMap = _aclAccountPolicyMapDao.findByAccountAndPolicy(acctId, policyId); + if (acctMap == null) { + // not there already + acctMap = new IAMAccountPolicyMapVO(acctId, policyId); + _aclAccountPolicyMapDao.persist(acctMap); + } + } + } + }); + + invalidateIAMCache(); + } + + @Override + public void removeIAMPolicyFromAccounts(final Long policyId, final List acctIds) { + IAMPolicy policy = _aclPolicyDao.findById(policyId); + if (policy == null) { + throw new InvalidParameterValueException("Unable to find acl policy: " + policyId + + "; failed to add policy to account."); + } + + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + // add entries in acl_group_policy_map table + for (Long acctId : acctIds) { + IAMAccountPolicyMapVO acctMap = _aclAccountPolicyMapDao.findByAccountAndPolicy(acctId, policyId); + if (acctMap != null) { + // exists + _aclAccountPolicyMapDao.remove(acctMap.getId()); + } + } + } + }); + + invalidateIAMCache(); + } + + @DB + @Override + public IAMPolicy addIAMPermissionToIAMPolicy(long iamPolicyId, String entityType, String scope, Long scopeId, + String action, String accessType, Permission perm, Boolean recursive) { + // get the Acl Policy entity + IAMPolicy policy = _aclPolicyDao.findById(iamPolicyId); + if (policy == null) { + throw new InvalidParameterValueException("Unable to find acl policy: " + iamPolicyId + + "; failed to add permission to policy."); + } + + // add entry in acl_policy_permission table + IAMPolicyPermissionVO permit = _policyPermissionDao.findByPolicyAndEntity(iamPolicyId, entityType, scope, + scopeId, action, perm, accessType); + if (permit == null) { + // not there already + permit = new IAMPolicyPermissionVO(iamPolicyId, action, entityType, accessType, scope, scopeId, perm, + recursive); + _policyPermissionDao.persist(permit); + } + + invalidateIAMCache(); + return policy; + + } + + @DB + @Override + public IAMPolicy removeIAMPermissionFromIAMPolicy(long iamPolicyId, String entityType, String scope, Long scopeId, + String action) { + // get the Acl Policy entity + IAMPolicy policy = _aclPolicyDao.findById(iamPolicyId); + if (policy == null) { + throw new InvalidParameterValueException("Unable to find acl policy: " + iamPolicyId + + "; failed to revoke permission from policy."); + } + // remove entry from acl_entity_permission table + IAMPolicyPermissionVO permit = _policyPermissionDao.findByPolicyAndEntity(iamPolicyId, entityType, scope, + scopeId, action, Permission.Allow, null); + if (permit != null) { + // not removed yet + _policyPermissionDao.remove(permit.getId()); + } + + invalidateIAMCache(); + return policy; + } + + @DB + @Override + public void removeIAMPermissionForEntity(final String entityType, final Long entityId) { + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + // remove entry from acl_entity_permission table + List permitList = _policyPermissionDao.listByEntity(entityType, entityId); + for (IAMPolicyPermissionVO permit : permitList) { + long policyId = permit.getAclPolicyId(); + _policyPermissionDao.remove(permit.getId()); + + // remove the policy if there are no other permissions + if ((_policyPermissionDao.listByPolicy(policyId)).isEmpty()) { + deleteIAMPolicy(policyId); + } + } + } + }); + + invalidateIAMCache(); + } + + @DB + @Override + public IAMPolicy resetIAMPolicy(long iamPolicyId) { + // get the Acl Policy entity + IAMPolicy policy = _aclPolicyDao.findById(iamPolicyId); + if (policy == null) { + throw new InvalidParameterValueException("Unable to find acl policy: " + iamPolicyId + + "; failed to reset the policy."); + } + + SearchBuilder sb = _policyPermissionDao.createSearchBuilder(); + sb.and("policyId", sb.entity().getAclPolicyId(), SearchCriteria.Op.EQ); + sb.and("scope", sb.entity().getScope(), SearchCriteria.Op.EQ); + sb.done(); + SearchCriteria permissionSC = sb.create(); + permissionSC.setParameters("policyId", iamPolicyId); + _policyPermissionDao.expunge(permissionSC); + + invalidateIAMCache(); + return policy; + } + + @Override + public boolean isActionAllowedForPolicies(String action, List policies) { + + boolean allowed = false; + + if (policies == null || policies.size() == 0) { + return allowed; + } + + List policyIds = new ArrayList(); + for (IAMPolicy policy : policies) { + policyIds.add(policy.getId()); + } + + SearchBuilder sb = _policyPermissionDao.createSearchBuilder(); + sb.and("action", sb.entity().getAction(), Op.EQ); + sb.and("policyId", sb.entity().getAclPolicyId(), Op.IN); + + SearchCriteria sc = sb.create(); + sc.setParameters("policyId", policyIds.toArray(new Object[policyIds.size()])); + sc.setParameters("action", action); + + List permissions = _policyPermissionDao.customSearch(sc, null); + + if (permissions != null && !permissions.isEmpty()) { + allowed = true; + } + + return allowed; + } + + + @Override + public List getGrantedEntities(long accountId, String action, String scope) { + // Get the static Policies of the Caller + List policies = listIAMPolicies(accountId); + // for each policy, find granted permission within the given scope + List entityIds = new ArrayList(); + for (IAMPolicy policy : policies) { + List pp = _policyPermissionDao.listByPolicyActionAndScope(policy.getId(), action, + scope, null); + if (pp != null) { + for (IAMPolicyPermissionVO p : pp) { + if (p.getScopeId() != null) { + entityIds.add(p.getScopeId()); + } + } + } + } + return entityIds; + } + + @Override + @SuppressWarnings("unchecked") + public List listPolicyPermissions(long policyId) { + @SuppressWarnings("rawtypes") + List pp = _policyPermissionDao.listByPolicy(policyId); + return pp; + } + + @SuppressWarnings("unchecked") + @Override + public List listPolicyPermissionsByScope(long policyId, String action, String scope, + String accessType) { + @SuppressWarnings("rawtypes") + List pp = _policyPermissionDao.listByPolicyActionAndScope(policyId, action, scope, accessType); + return pp; + } + + @SuppressWarnings("unchecked") + @Override + public List listPolicyPermissionByActionAndEntity(long policyId, String action, + String entityType) { + @SuppressWarnings("rawtypes") + List pp = _policyPermissionDao.listByPolicyActionAndEntity(policyId, action, entityType); + return pp; + } + + @SuppressWarnings("unchecked") + @Override + public List listPolicyPermissionByAccessAndEntity(long policyId, String accessType, + String entityType) { + @SuppressWarnings("rawtypes") + List pp = _policyPermissionDao.listByPolicyAccessAndEntity(policyId, accessType, entityType); + return pp; + } + + @Override + public IAMPolicy getResourceOwnerPolicy() { + return _aclPolicyDao.findByName("RESOURCE_OWNER"); + } + + // search for policy with only one resource grant permission + @Override + public IAMPolicy getResourceGrantPolicy(String entityType, Long entityId, String accessType, String action) { + List policyList = _aclPolicyDao.listAll(); + for (IAMPolicyVO policy : policyList) { + List pp = listPolicyPermissions(policy.getId()); + if (pp != null && pp.size() == 1) { + // resource grant policy should only have one ACL permission assigned + IAMPolicyPermission permit = pp.get(0); + if (permit.getEntityType().equals(entityType) && permit.getScope().equals(PermissionScope.RESOURCE.toString()) + && permit.getScopeId().longValue() == entityId.longValue()) { + if (accessType != null && permit.getAccessType().equals(accessType)) { + return policy; + } else if (action != null && permit.getAction().equals(action)) { + return policy; + } + } + } + } + return null; + } + +} diff --git a/services/iam/server/src/org/apache/cloudstack/iam/server/dao/IAMPolicyPermissionDao.java b/services/iam/server/src/org/apache/cloudstack/iam/server/dao/IAMPolicyPermissionDao.java index 6e6099c6648..ebb4916470d 100644 --- a/services/iam/server/src/org/apache/cloudstack/iam/server/dao/IAMPolicyPermissionDao.java +++ b/services/iam/server/src/org/apache/cloudstack/iam/server/dao/IAMPolicyPermissionDao.java @@ -27,7 +27,7 @@ public interface IAMPolicyPermissionDao extends GenericDao listByPolicy(long policyId); IAMPolicyPermissionVO findByPolicyAndEntity(long policyId, String entityType, String scope, Long scopeId, - String action, Permission perm); + String action, Permission perm, String accessType); List listByPolicyActionAndScope(long policyId, String action, String scope, String accessType); diff --git a/services/iam/server/src/org/apache/cloudstack/iam/server/dao/IAMPolicyPermissionDaoImpl.java b/services/iam/server/src/org/apache/cloudstack/iam/server/dao/IAMPolicyPermissionDaoImpl.java index 9cc1af07e8c..44b77d1163e 100644 --- a/services/iam/server/src/org/apache/cloudstack/iam/server/dao/IAMPolicyPermissionDaoImpl.java +++ b/services/iam/server/src/org/apache/cloudstack/iam/server/dao/IAMPolicyPermissionDaoImpl.java @@ -70,7 +70,7 @@ public class IAMPolicyPermissionDaoImpl extends GenericDaoBase sc = fullSearch.create(); sc.setParameters("policyId", policyId); sc.setParameters("entityType", entityType); @@ -78,6 +78,11 @@ public class IAMPolicyPermissionDaoImpl extends GenericDaoBaseconsole-proxy console-proxy-rdp/rdpconsole secondary-storage - iam diff --git a/test/integration/smoke/test_vm_iam.py b/test/integration/smoke/test_vm_iam.py deleted file mode 100644 index be75a79737f..00000000000 --- a/test/integration/smoke/test_vm_iam.py +++ /dev/null @@ -1,719 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -""" BVT tests for Virtual Machine IAM effect -""" -#Import Local Modules -import marvin -from marvin.cloudstackTestCase import * -from marvin.cloudstackAPI import * -from marvin.lib.utils import * -from marvin.lib.base import * -from marvin.lib.common import * -from marvin.codes import FAILED -from nose.plugins.attrib import attr -#Import System modules -import time - -_multiprocess_shared_ = True -class Services: - """Test VM Life Cycle Services - """ - - def __init__(self): - self.services = { - #data for domains and accounts - "domain1": { - "name": "Domain1", - }, - "account1A": { - "email": "test1A@test.com", - "firstname": "test1A", - "lastname": "User", - "username": "test1A", - "password": "password", - }, - "account1B": { - "email": "test1B@test.com", - "firstname": "test1B", - "lastname": "User", - "username": "test1B", - "password": "password", - }, - "domain2": { - "name": "Domain2", - }, - "account2A": { - "email": "test2A@test.com", - "firstname": "test2A", - "lastname": "User", - "username": "test2A", - "password": "password", - }, - #data reqd for virtual machine creation - "virtual_machine1A" : { - "name" : "test1Avm", - "displayname" : "Test1A VM", - }, - "virtual_machine1B" : { - "name" : "test1Bvm", - "displayname" : "Test1B VM", - }, - "virtual_machine2A" : { - "name" : "test2Avm", - "displayname" : "Test2A VM", - }, - #small service offering - "service_offering": { - "small": { - "name": "Small Instance", - "displaytext": "Small Instance", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - }, - }, - "ostype": 'CentOS 5.6 (64-bit)', - # iam group and policy information - "service_desk_iam_grp" : { - "name" : "Service Desk", - "description" : "Service Desk IAM Group" - }, - "vm_readonly_iam_policy" : { - "name" : "VM Read Only Access", - "description" : "VM read only access iam policy" - }, - } - - - -class TestVMIam(cloudstackTestCase): - - @classmethod - def setUpClass(self): - testClient = super(TestVMIam, self).getClsTestClient() - self.apiclient = testClient.getApiClient() - self.services = Services().services - - # backup default apikey and secretkey - self.default_apikey = self.apiclient.connection.apiKey - self.default_secretkey = self.apiclient.connection.securityKey - - # Create domains and accounts etc - self.domain_1 = Domain.create( - self.apiclient, - self.services["domain1"] - ) - self.domain_2 = Domain.create( - self.apiclient, - self.services["domain2"] - ) - # Create two accounts for doamin_1 - self.account_1A = Account.create( - self.apiclient, - self.services["account1A"], - admin=False, - domainid=self.domain_1.id - ) - - self.account_1B = Account.create( - self.apiclient, - self.services["account1B"], - admin=False, - domainid=self.domain_1.id - ) - - # Create an account for domain_2 - self.account_2A = Account.create( - self.apiclient, - self.services["account2A"], - admin=False, - domainid=self.domain_2.id - ) - - # Fetch user details to register apiKey for them - self.user_1A = User.list( - self.apiclient, - account=self.account_1A.name, - domainid=self.account_1A.domainid - )[0] - - user_1A_key = User.registerUserKeys( - self.apiclient, - self.user_1A.id - ) - self.user_1A_apikey = user_1A_key.apikey - self.user_1A_secretkey = user_1A_key.secretkey - - - self.user_1B = User.list( - self.apiclient, - account=self.account_1B.name, - domainid=self.account_1B.domainid - )[0] - - user_1B_key = User.registerUserKeys( - self.apiclient, - self.user_1B.id - ) - - self.user_1B_apikey = user_1B_key.apikey - self.user_1B_secretkey = user_1B_key.secretkey - - - self.user_2A = User.list( - self.apiclient, - account=self.account_2A.name, - domainid=self.account_2A.domainid - )[0] - - user_2A_key = User.registerUserKeys( - self.apiclient, - self.user_2A.id - ) - self.user_2A_apikey = user_2A_key.apikey - self.user_2A_secretkey = user_2A_key.secretkey - - # create service offering - self.service_offering = ServiceOffering.create( - self.apiclient, - self.services["service_offering"]["small"] - ) - - self.zone = get_zone(self.apiclient, testClient.getZoneForTests()) - self.services['mode'] = self.zone.networktype - self.template = get_template(self.apiclient, self.zone.id, self.services["ostype"]) - - # deploy 3 VMs for three accounts - self.virtual_machine_1A = VirtualMachine.create( - self.apiclient, - self.services["virtual_machine1A"], - accountid=self.account_1A.name, - zoneid=self.zone.id, - domainid=self.account_1A.domainid, - serviceofferingid=self.service_offering.id, - templateid=self.template.id - ) - - self.virtual_machine_1B = VirtualMachine.create( - self.apiclient, - self.services["virtual_machine1B"], - accountid=self.account_1B.name, - zoneid=self.zone.id, - domainid=self.account_1B.domainid, - serviceofferingid=self.service_offering.id, - templateid=self.template.id - ) - - self.virtual_machine_2A = VirtualMachine.create( - self.apiclient, - self.services["virtual_machine2A"], - accountid=self.account_2A.name, - zoneid=self.zone.id, - domainid=self.account_2A.domainid, - serviceofferingid=self.service_offering.id, - templateid=self.template.id - ) - - self.srv_desk_grp = IAMGroup.create( - self.apiclient, - self.services["service_desk_iam_grp"] - ) - - self.vm_read_policy = IAMPolicy.create( - self.apiclient, - self.services["vm_readonly_iam_policy"] - ) - - self.srv_desk_grp.attachPolicy( - self.apiclient, [self.vm_read_policy] - ) - - vm_grant_policy_params = {} - vm_grant_policy_params['name'] = "policyGrantVirtualMachine" + self.virtual_machine_1A.id - vm_grant_policy_params['description'] = "Policy to grant permission to VirtualMachine " + self.virtual_machine_1A.id - self.vm_grant_policy = IAMPolicy.create( - self.apiclient, - vm_grant_policy_params - ) - - self._cleanup = [ - self.account_1A, - self.account_1B, - self.domain_1, - self.account_2A, - self.domain_2, - self.service_offering, - self.vm_read_policy, - self.srv_desk_grp, - self.vm_grant_policy - ] - - @classmethod - def tearDownClass(self): - self.apiclient = super(TestVMIam, self).getClsTestClient().getApiClient() - cleanup_resources(self.apiclient, self._cleanup) - return - - def setUp(self): - self.apiclient = self.testClient.getApiClient() - self.dbclient = self.testClient.getDbConnection() - self.cleanup = [] - - def tearDown(self): - # restore back default apikey and secretkey - self.apiclient.connection.apiKey = self.default_apikey - self.apiclient.connection.securityKey = self.default_secretkey - cleanup_resources(self.apiclient, self.cleanup) - return - - - - @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg", "selfservice"]) - def test_01_list_own_vm(self): - # listVM command should return owne's VM - - self.debug("Listing VM for account: %s" % self.account_1A.name) - - self.apiclient.connection.apiKey = self.user_1A_apikey - self.apiclient.connection.securityKey = self.user_1A_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 1, - "Check VM available in List Virtual Machines" - ) - - self.assertEqual( - list_vm_response[0].name, - self.virtual_machine_1A.name, - "Virtual Machine names do not match" - ) - - self.debug("Listing VM for account: %s" % self.account_1B.name) - self.apiclient.connection.apiKey = self.user_1B_apikey - self.apiclient.connection.securityKey = self.user_1B_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 1, - "Check VM available in List Virtual Machines" - ) - - self.assertEqual( - list_vm_response[0].name, - self.virtual_machine_1B.name, - "Virtual Machine names do not match" - ) - - self.debug("Listing VM for account: %s" % self.account_2A.name) - - self.apiclient.connection.apiKey = self.user_2A_apikey - self.apiclient.connection.securityKey = self.user_2A_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 1, - "Check VM available in List Virtual Machines" - ) - - self.assertEqual( - list_vm_response[0].name, - self.virtual_machine_2A.name, - "Virtual Machine names do not match" - ) - - return - - @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg", "selfservice"]) - def test_02_grant_domain_vm(self): - - # Validate the following - # 1. Grant domain2 VM access to account_1B - # 2. listVM command should return account_1B and domain_2 VMs. - - self.debug("Granting Domain %s VM read only access to account: %s" % (self.domain_2.name, self.account_1B.name)) - - self.srv_desk_grp.addAccount(self.apiclient, [self.account_1B]) - domain_permission = {} - domain_permission['action'] = "listVirtualMachines" - domain_permission['entitytype'] = "VirtualMachine" - domain_permission['scope'] = "DOMAIN" - domain_permission['scopeid'] = self.domain_2.id - self.vm_read_policy.addPermission(self.apiclient, domain_permission) - - self.debug("Listing VM for account: %s" % self.account_1B.name) - self.apiclient.connection.apiKey = self.user_1B_apikey - self.apiclient.connection.securityKey = self.user_1B_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 2, - "Check VM available in List Virtual Machines" - ) - - list_vm_names = [list_vm_response[0].name, list_vm_response[1].name] - - self.assertEqual( self.virtual_machine_1B.name in list_vm_names, - True, - "Accessible Virtual Machine names do not match" - ) - - self.assertEqual( self.virtual_machine_2A.name in list_vm_names, - True, - "Accessible Virtual Machine names do not match" - ) - - return - - - @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg", "selfservice"]) - def test_03_grant_account_vm(self): - - # Validate the following - # 1. Grant account_1A VM access to account_1B - # 2. listVM command should return account_1A and account_1B VMs. - - self.debug("Granting Account %s VM read only access to account: %s" % (self.account_1A.name, self.account_1B.name)) - - account_permission = {} - account_permission['action'] = "listVirtualMachines" - account_permission['entitytype'] = "VirtualMachine" - account_permission['scope'] = "ACCOUNT" - account_permission['scopeid'] = self.account_1A.id - self.vm_read_policy.addPermission(self.apiclient, account_permission) - - self.debug("Listing VM for account: %s" % self.account_1B.name) - self.apiclient.connection.apiKey = self.user_1B_apikey - self.apiclient.connection.securityKey = self.user_1B_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 3, - "Check VM available in List Virtual Machines" - ) - - list_vm_names = [list_vm_response[0].name, list_vm_response[1].name, list_vm_response[2].name] - - self.assertEqual( self.virtual_machine_1B.name in list_vm_names, - True, - "Accessible Virtual Machine names do not match" - ) - - self.assertEqual( self.virtual_machine_1A.name in list_vm_names, - True, - "Accessible Virtual Machine names do not match" - ) - - self.assertEqual( self.virtual_machine_2A.name in list_vm_names, - True, - "Accessible Virtual Machine names do not match" - ) - - return - - - @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg", "selfservice"]) - def test_04_revoke_account_vm(self): - - # Validate the following - # 1. Revoke account_1A VM access from account_1B - # 2. listVM command should not return account_1A VMs. - - self.debug("Revoking Account %s VM read only access from account: %s" % (self.account_1A.name, self.account_1B.name)) - - account_permission = {} - account_permission['action'] = "listVirtualMachines" - account_permission['entitytype'] = "VirtualMachine" - account_permission['scope'] = "ACCOUNT" - account_permission['scopeid'] = self.account_1A.id - self.vm_read_policy.removePermission(self.apiclient, account_permission) - - self.debug("Listing VM for account: %s" % self.account_1B.name) - self.apiclient.connection.apiKey = self.user_1B_apikey - self.apiclient.connection.securityKey = self.user_1B_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 2, - "Check VM available in List Virtual Machines" - ) - - list_vm_names = [list_vm_response[0].name, list_vm_response[1].name] - - - self.assertEqual( self.virtual_machine_1A.name in list_vm_names, - False, - "Accessible Virtual Machine names do not match" - ) - return - - - @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg", "selfservice"]) - def test_05_revoke_domain_vm(self): - - # Validate the following - # 1. Revoke account_1A VM access from account_1B - # 2. listVM command should not return account_1A VMs. - - self.debug("Revoking Domain %s VM read only access from account: %s" % (self.domain_1.name, self.account_1B.name)) - - domain_permission = {} - domain_permission['action'] = "listVirtualMachines" - domain_permission['entitytype'] = "VirtualMachine" - domain_permission['scope'] = "DOMAIN" - domain_permission['scopeid'] = self.domain_2.id - self.vm_read_policy.removePermission(self.apiclient, domain_permission) - - self.debug("Listing VM for account: %s" % self.account_1B.name) - self.apiclient.connection.apiKey = self.user_1B_apikey - self.apiclient.connection.securityKey = self.user_1B_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 1, - "Check VM available in List Virtual Machines" - ) - - self.assertEqual( - list_vm_response[0].name, - self.virtual_machine_1B.name, - "Virtual Machine names do not match" - ) - - return - - @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg", "selfservice"]) - def test_06_grant_resource_vm(self): - - # Validate the following - # 1. Grant a particular vm access to account_1B - # 2. listVM command should return account_1B VMs and granted VM. - - self.debug("Granting VM %s read only access to account: %s" % (self.virtual_machine_1A.name, self.account_1B.name)) - - res_permission = {} - res_permission['action'] = "listVirtualMachines" - res_permission['entitytype'] = "VirtualMachine" - res_permission['scope'] = "RESOURCE" - res_permission['scopeid'] = self.virtual_machine_1A.id - self.vm_read_policy.addPermission(self.apiclient, res_permission) - - self.debug("Listing VM for account: %s" % self.account_1B.name) - self.apiclient.connection.apiKey = self.user_1B_apikey - self.apiclient.connection.securityKey = self.user_1B_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 2, - "Check VM available in List Virtual Machines" - ) - - list_vm_names = [list_vm_response[0].name, list_vm_response[1].name] - - self.assertEqual( self.virtual_machine_1B.name in list_vm_names, - True, - "Accessible Virtual Machine names do not match" - ) - - self.assertEqual( self.virtual_machine_1A.name in list_vm_names, - True, - "Accessible Virtual Machine names do not match" - ) - - return - - @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg", "selfservice"]) - def test_07_revoke_resource_vm(self): - - # Validate the following - # 1. Grant a particular vm access to account_1B - # 2. listVM command should return account_1B VMs and granted VM. - - self.debug("Revoking VM %s read only access from account: %s" % (self.virtual_machine_1A.name, self.account_1B.name)) - - res_permission = {} - res_permission['action'] = "listVirtualMachines" - res_permission['entitytype'] = "VirtualMachine" - res_permission['scope'] = "RESOURCE" - res_permission['scopeid'] = self.virtual_machine_1A.id - self.vm_read_policy.removePermission(self.apiclient, res_permission) - - self.debug("Listing VM for account: %s" % self.account_1B.id) - self.apiclient.connection.apiKey = self.user_1B_apikey - self.apiclient.connection.securityKey = self.user_1B_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 1, - "Check VM available in List Virtual Machines" - ) - - self.assertEqual( - list_vm_response[0].name, - self.virtual_machine_1B.name, - "Virtual Machine names do not match" - ) - - return - - - @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg", "selfservice"]) - def test_08_policy_attach_account(self): - - # Validate the following - # 1. Grant a particular vm access to account_1B by directly attaching policy to account - # 2. listVM command should return account_1B VMs and granted VM. - - self.debug("Granting VM %s read only access to account: %s by attaching policy to account" % (self.virtual_machine_1A.name, self.account_1B.name)) - - res_permission = {} - res_permission['action'] = "listVirtualMachines" - res_permission['entitytype'] = "VirtualMachine" - res_permission['scope'] = "RESOURCE" - res_permission['scopeid'] = self.virtual_machine_1A.id - self.vm_grant_policy.addPermission(self.apiclient, res_permission) - self.vm_grant_policy.attachAccount(self.apiclient, [self.account_1B]) - - self.debug("Listing VM for account: %s" % self.account_1B.id) - self.apiclient.connection.apiKey = self.user_1B_apikey - self.apiclient.connection.securityKey = self.user_1B_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 2, - "Check VM available in List Virtual Machines" - ) - - list_vm_names = [list_vm_response[0].name, list_vm_response[1].name] - - self.assertEqual( self.virtual_machine_1B.name in list_vm_names, - True, - "Accessible Virtual Machine names do not match" - ) - - self.assertEqual( self.virtual_machine_1A.name in list_vm_names, - True, - "Accessible Virtual Machine names do not match" - ) - - return - - @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg", "selfservice"]) - def test_09_policy_detach_account(self): - - # Validate the following - # 1. Revoking a particular vm access from account_1B by detaching policy from account - # 2. listVM command should return account_1B VMs. - - self.debug("Revoking VM %s read only access from account: %s by detaching policy from account" % (self.virtual_machine_1A.name, self.account_1B.name)) - - self.vm_grant_policy.detachAccount(self.apiclient, [self.account_1B]) - - self.debug("Listing VM for account: %s" % self.account_1B.id) - self.apiclient.connection.apiKey = self.user_1B_apikey - self.apiclient.connection.securityKey = self.user_1B_secretkey - list_vm_response = list_virtual_machines( - self.apiclient - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(list_vm_response), - 1, - "Check VM available in List Virtual Machines" - ) - - self.assertEqual( - list_vm_response[0].name, - self.virtual_machine_1B.name, - "Virtual Machine names do not match" - ) - - return \ No newline at end of file