Search in sources :

Example 26 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method disableAccount.

@Override
@ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DISABLE, eventDescription = "disabling account", async = true)
public AccountVO disableAccount(final String accountName, final Long domainId, final Long accountId) throws ConcurrentOperationException, ResourceUnavailableException {
    final Account caller = CallContext.current().getCallingAccount();
    final Account account;
    if (accountId != null) {
        account = _accountDao.findById(accountId);
    } else {
        account = _accountDao.findActiveAccount(accountName, domainId);
    }
    if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId);
    }
    if (account.getId() == Account.ACCOUNT_ID_SYSTEM) {
        throw new PermissionDeniedException("Account id : " + accountId + " is a system account, disable is not allowed");
    }
    checkAccess(caller, AccessType.OperateEntry, true, account);
    if (disableAccount(account.getId())) {
        CallContext.current().putContextParameter(Account.class, account.getUuid());
        return _accountDao.findById(account.getId());
    } else {
        throw new CloudRuntimeException("Unable to update account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId);
    }
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent)

Example 27 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method buildACLSearchParameters.

// TODO: deprecate this to use the new buildACLSearchParameters with permittedDomains, permittedAccounts, and permittedResources as return
@Override
public void buildACLSearchParameters(final Account caller, final Long id, final String accountName, final Long projectId, final List<Long> permittedAccounts, final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject, final boolean listAll, final boolean forProjectInvitation) {
    final Long domainId = domainIdRecursiveListProject.first();
    if (domainId != null) {
        final 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");
        }
        final Account userAccount;
        final Domain domain;
        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 {
                final 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());
            }
        }
    }
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) Project(com.cloud.projects.Project) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) Domain(com.cloud.legacymodel.domain.Domain)

Example 28 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method checkAccess.

@Override
public void checkAccess(final Account caller, final AccessType accessType, final boolean sameOwner, final String apiName, final ControlledEntity... entities) {
    // check for the same owner
    Long ownerId = null;
    ControlledEntity prevEntity = null;
    if (sameOwner) {
        for (final 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;
            }
        }
    }
    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;
    }
    final HashMap<Long, List<ControlledEntity>> domains = new HashMap<>();
    for (final 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
            final 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<ControlledEntity> 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 (final 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;
            }
        }
        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);
        }
    }
    for (final Map.Entry<Long, List<ControlledEntity>> domain : domains.entrySet()) {
        for (final SecurityChecker checker : _securityCheckers) {
            final 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 (final PermissionDeniedException e) {
                e.addDetails(caller, domain.getValue());
                throw e;
            }
        }
    }
// check that resources belong to the same account
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) VirtualMachineTemplate(com.cloud.legacymodel.storage.VirtualMachineTemplate) HashMap(java.util.HashMap) SecurityChecker(com.cloud.acl.SecurityChecker) AffinityGroup(com.cloud.affinity.AffinityGroup) ControlledEntity(com.cloud.legacymodel.acl.ControlledEntity) Network(com.cloud.legacymodel.network.Network) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ArrayList(java.util.ArrayList) List(java.util.List) Domain(com.cloud.legacymodel.domain.Domain) Map(java.util.Map) HashMap(java.util.HashMap)

Example 29 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class TemplateManagerImpl method updateTemplateOrIso.

private VMTemplateVO updateTemplateOrIso(final BaseUpdateTemplateOrIsoCmd cmd) {
    final Long id = cmd.getId();
    final String name = cmd.getTemplateName();
    final String displayText = cmd.getDisplayText();
    final String format = cmd.getFormat();
    final Long guestOSId = cmd.getOsTypeId();
    final Boolean passwordEnabled = cmd.getPasswordEnabled();
    final Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
    final Boolean isRoutingTemplate = cmd.isRoutingType();
    final Boolean bootable = cmd.getBootable();
    final Integer sortKey = cmd.getSortKey();
    final Map details = cmd.getDetails();
    final Account account = CallContext.current().getCallingAccount();
    final String url = cmd.getUrl();
    final OptimiseFor optimiseFor = cmd.getOptimiseFor();
    final String manufacturerString = cmd.getManufacturerString();
    final String cpuFlags = cmd.getCpuFlags();
    final Boolean macLearning = cmd.getMacLearning();
    final MaintenancePolicy maintenancePolicy = cmd.getMaintenancePolicy();
    final Boolean isRemoteGatewayTemplate = cmd.getIsRemoteGatewayTemplate();
    // verify that template exists
    VMTemplateVO template = this._tmpltDao.findById(id);
    if (template == null || template.getRemoved() != null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id");
        ex.addProxyObject(String.valueOf(id), "templateId");
        throw ex;
    }
    verifyTemplateId(id);
    // do a permission check
    this._accountMgr.checkAccess(account, AccessType.OperateEntry, true, template);
    if (cmd.isRoutingType() != null) {
        if (!this._accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
        }
    }
    // update is needed if any of the fields below got filled by the user
    final boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && optimiseFor == null && manufacturerString == null && isRemoteGatewayTemplate == null && cpuFlags == null && macLearning == null && passwordEnabled == null && bootable == null && sortKey == null && isDynamicallyScalable == null && isRoutingTemplate == null && url == null && details == null);
    if (!updateNeeded) {
        return template;
    }
    template = this._tmpltDao.createForUpdate(id);
    if (name != null) {
        template.setName(name);
    }
    if (displayText != null) {
        template.setDisplayText(displayText);
    }
    if (sortKey != null) {
        template.setSortKey(sortKey);
    }
    if (optimiseFor != null) {
        template.setOptimiseFor(optimiseFor);
    }
    if (manufacturerString != null) {
        template.setManufacturerString(manufacturerString);
    }
    if (cpuFlags != null) {
        template.setCpuFlags(cpuFlags);
    }
    if (macLearning != null) {
        template.setMacLearning(macLearning);
    }
    if (maintenancePolicy != null) {
        template.setMaintenancePolicy(maintenancePolicy);
    }
    if (isRemoteGatewayTemplate != null) {
        template.setRemoteGatewayTemplate(isRemoteGatewayTemplate);
    }
    final ImageFormat imageFormat;
    if (format != null) {
        try {
            imageFormat = ImageFormat.valueOf(format.toUpperCase());
        } catch (final IllegalArgumentException e) {
            throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
        }
        template.setFormat(imageFormat);
    }
    if (guestOSId != null) {
        final long oldGuestOSId = template.getGuestOSId();
        final GuestOSVO guestOS = this._guestOSDao.findById(guestOSId);
        if (guestOS == null) {
            throw new InvalidParameterValueException("Please specify a valid guest OS ID.");
        } else {
            template.setGuestOSId(guestOSId);
        }
        if (guestOSId != oldGuestOSId) {
            // vm guest os type need to be updated if template guest os id changes.
            final SearchCriteria<VMInstanceVO> sc = this._vmInstanceDao.createSearchCriteria();
            sc.addAnd("templateId", SearchCriteria.Op.EQ, id);
            sc.addAnd("state", SearchCriteria.Op.NEQ, State.Expunging);
            final List<VMInstanceVO> vms = this._vmInstanceDao.search(sc, null);
            if (vms != null && !vms.isEmpty()) {
                for (final VMInstanceVO vm : vms) {
                    vm.setGuestOSId(guestOSId);
                    this._vmInstanceDao.update(vm.getId(), vm);
                }
            }
        }
    }
    if (passwordEnabled != null) {
        template.setEnablePassword(passwordEnabled);
    }
    if (bootable != null) {
        template.setBootable(bootable);
    }
    if (isDynamicallyScalable != null) {
        template.setDynamicallyScalable(isDynamicallyScalable);
    }
    if (url != null) {
        template.setUrl(url);
    }
    if (isRoutingTemplate != null) {
        if (isRoutingTemplate) {
            template.setTemplateType(TemplateType.ROUTING);
        } else {
            template.setTemplateType(TemplateType.USER);
        }
    }
    if (details != null && !details.isEmpty()) {
        template.setDetails(details);
        this._tmpltDao.saveDetails(template);
    }
    this._tmpltDao.update(id, template);
    return this._tmpltDao.findById(id);
}
Also used : Account(com.cloud.legacymodel.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) GuestOSVO(com.cloud.storage.GuestOSVO) OptimiseFor(com.cloud.model.enumeration.OptimiseFor) ImageFormat(com.cloud.model.enumeration.ImageFormat) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) MaintenancePolicy(com.cloud.model.enumeration.MaintenancePolicy) Map(java.util.Map) HashMap(java.util.HashMap)

Example 30 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class TemplateManagerImpl method extract.

private String extract(final Account caller, final Long templateId, final String url, final Long zoneId, final String mode, final Long eventId, final boolean isISO) {
    String desc = Upload.Type.TEMPLATE.toString();
    if (isISO) {
        desc = Upload.Type.ISO.toString();
    }
    if (!this._accountMgr.isRootAdmin(caller.getId()) && this._disableExtraction) {
        throw new PermissionDeniedException("Extraction has been disabled by admin");
    }
    final VMTemplateVO template = this._tmpltDao.findById(templateId);
    if (template == null || template.getRemoved() != null) {
        throw new InvalidParameterValueException("Unable to find " + desc + " with id " + templateId);
    }
    if (template.getTemplateType() == TemplateType.SYSTEM) {
        throw new InvalidParameterValueException("Unable to extract the " + desc + " " + template.getName() + " as it is a default System template");
    } else if (template.getTemplateType() == TemplateType.PERHOST) {
        throw new InvalidParameterValueException("Unable to extract the " + desc + " " + template.getName() + " as it resides on host and not on SSVM");
    }
    if (isISO) {
        if (template.getFormat() != ImageFormat.ISO) {
            throw new InvalidParameterValueException("Unsupported format, could not extract the ISO");
        }
    } else {
        if (template.getFormat() == ImageFormat.ISO) {
            throw new InvalidParameterValueException("Unsupported format, could not extract the template");
        }
    }
    if (zoneId != null && this._dcDao.findById(zoneId) == null) {
        throw new IllegalArgumentException("Please specify a valid zone.");
    }
    if (!this._accountMgr.isRootAdmin(caller.getId()) && !template.isExtractable()) {
        throw new InvalidParameterValueException("Unable to extract template id=" + templateId + " as it's not extractable");
    }
    this._accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template);
    final List<DataStore> ssStores = this._dataStoreMgr.getImageStoresByScope(new ZoneScope(null));
    TemplateDataStoreVO tmpltStoreRef = null;
    ImageStoreEntity tmpltStore = null;
    if (ssStores != null) {
        for (final DataStore store : ssStores) {
            tmpltStoreRef = this._tmplStoreDao.findByStoreTemplate(store.getId(), templateId);
            if (tmpltStoreRef != null) {
                if (tmpltStoreRef.getDownloadState() == VMTemplateStatus.DOWNLOADED) {
                    tmpltStore = (ImageStoreEntity) store;
                    break;
                }
            }
        }
    }
    if (tmpltStore == null) {
        throw new InvalidParameterValueException("The " + desc + " has not been downloaded ");
    }
    // Check if the url already exists
    if (tmpltStoreRef.getExtractUrl() != null) {
        return tmpltStoreRef.getExtractUrl();
    }
    // Handle NFS to S3 object store migration case, we trigger template sync from NFS to S3 during extract template or copy template
    this._tmpltSvr.syncTemplateToRegionStore(templateId, tmpltStore);
    final TemplateInfo templateObject = this._tmplFactory.getTemplate(templateId, tmpltStore);
    final String extractUrl = tmpltStore.createEntityExtractUrl(templateObject.getInstallPath(), template.getFormat(), templateObject);
    tmpltStoreRef.setExtractUrl(extractUrl);
    tmpltStoreRef.setExtractUrlCreated(DateUtil.now());
    this._tmplStoreDao.update(tmpltStoreRef.getId(), tmpltStoreRef);
    return extractUrl;
}
Also used : ZoneScope(com.cloud.engine.subsystem.api.storage.ZoneScope) TemplateInfo(com.cloud.engine.subsystem.api.storage.TemplateInfo) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) VMTemplateVO(com.cloud.storage.VMTemplateVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ImageStoreEntity(com.cloud.storage.image.datastore.ImageStoreEntity) TemplateDataStoreVO(com.cloud.storage.datastore.db.TemplateDataStoreVO)

Aggregations

PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)73 Account (com.cloud.legacymodel.user.Account)64 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)59 ActionEvent (com.cloud.event.ActionEvent)26 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)25 ArrayList (java.util.ArrayList)14 UserAccount (com.cloud.legacymodel.user.UserAccount)13 DB (com.cloud.utils.db.DB)13 DataCenterVO (com.cloud.dc.DataCenterVO)11 HashMap (java.util.HashMap)11 DomainVO (com.cloud.domain.DomainVO)9 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)9 Project (com.cloud.projects.Project)9 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)8 Pair (com.cloud.legacymodel.utils.Pair)8 VMTemplateVO (com.cloud.storage.VMTemplateVO)8 TransactionStatus (com.cloud.utils.db.TransactionStatus)8 List (java.util.List)8 Domain (com.cloud.legacymodel.domain.Domain)7 VolumeVO (com.cloud.storage.VolumeVO)7