Search in sources :

Example 6 with BaseCmd

use of org.apache.cloudstack.api.BaseCmd in project cloudstack by apache.

the class FakeCmdWithRoleAdmin method driveAuthTest.

protected void driveAuthTest(final short type) {
    // Prepare
    final BaseCmd cmd = new FakeCmdWithRoleAdmin();
    final Account account = mock(Account.class);
    ((FakeCmdWithRoleAdmin) cmd).account = account;
    when(account.getType()).thenReturn(type);
    User user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
    CallContext.register(user, account);
    final Map<String, String> params = new HashMap<String, String>();
    params.put(ApiConstants.COMMAND, "");
    params.put("addedParam", "");
    params.put("paramWithRole", "");
    // Execute
    try {
        driveTest(cmd, params);
    } finally {
        CallContext.unregister();
    }
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) UserVO(com.cloud.user.UserVO) HashMap(java.util.HashMap) BaseCmd(org.apache.cloudstack.api.BaseCmd)

Example 7 with BaseCmd

use of org.apache.cloudstack.api.BaseCmd in project cloudstack by apache.

the class ApiServer method handleRequest.

@Override
@SuppressWarnings("rawtypes")
public String handleRequest(final Map params, final String responseType, final StringBuilder auditTrailSb) throws ServerApiException {
    checkCharacterInkParams(params);
    String response = null;
    String[] command = null;
    try {
        command = (String[]) params.get("command");
        if (command == null) {
            s_logger.error("invalid request, no command sent");
            if (s_logger.isTraceEnabled()) {
                s_logger.trace("dumping request parameters");
                for (final Object key : params.keySet()) {
                    final String keyStr = (String) key;
                    final String[] value = (String[]) params.get(key);
                    s_logger.trace("   key: " + keyStr + ", value: " + ((value == null) ? "'null'" : value[0]));
                }
            }
            throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "Invalid request, no command sent");
        } else {
            // Don't allow Login/Logout APIs to go past this point
            if (authManager.getAPIAuthenticator(command[0]) != null) {
                return null;
            }
            final Map<String, String> paramMap = new HashMap<String, String>();
            final Set keys = params.keySet();
            final Iterator keysIter = keys.iterator();
            while (keysIter.hasNext()) {
                final String key = (String) keysIter.next();
                if ("command".equalsIgnoreCase(key)) {
                    continue;
                }
                final String[] value = (String[]) params.get(key);
                paramMap.put(key, value[0]);
            }
            Class<?> cmdClass = getCmdClass(command[0]);
            if (cmdClass != null) {
                APICommand annotation = cmdClass.getAnnotation(APICommand.class);
                if (annotation == null) {
                    s_logger.error("No APICommand annotation found for class " + cmdClass.getCanonicalName());
                    throw new CloudRuntimeException("No APICommand annotation found for class " + cmdClass.getCanonicalName());
                }
                BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance();
                cmdObj = ComponentContext.inject(cmdObj);
                cmdObj.configure();
                cmdObj.setFullUrlParams(paramMap);
                cmdObj.setResponseType(responseType);
                cmdObj.setHttpMethod(paramMap.get(ApiConstants.HTTPMETHOD).toString());
                // This is where the command is either serialized, or directly dispatched
                StringBuilder log = new StringBuilder();
                response = queueCommand(cmdObj, paramMap, log);
                buildAuditTrail(auditTrailSb, command[0], log.toString());
            } else {
                final String errorString = "Unknown API command: " + command[0];
                s_logger.warn(errorString);
                auditTrailSb.append(" " + errorString);
                throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString);
            }
        }
    } catch (final InvalidParameterValueException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
    } catch (final IllegalArgumentException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
    } catch (final PermissionDeniedException ex) {
        final ArrayList<ExceptionProxyObject> idList = ex.getIdProxyList();
        if (idList != null) {
            final StringBuffer buf = new StringBuffer();
            for (final ExceptionProxyObject obj : idList) {
                buf.append(obj.getDescription());
                buf.append(":");
                buf.append(obj.getUuid());
                buf.append(" ");
            }
            s_logger.info("PermissionDenied: " + ex.getMessage() + " on objs: [" + buf.toString() + "]");
        } else {
            s_logger.info("PermissionDenied: " + ex.getMessage());
        }
        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, ex.getMessage(), ex);
    } catch (final AccountLimitException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.ACCOUNT_RESOURCE_LIMIT_ERROR, ex.getMessage(), ex);
    } catch (final InsufficientCapacityException ex) {
        s_logger.info(ex.getMessage());
        String errorMsg = ex.getMessage();
        if (!accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
            // hide internal details to non-admin user for security reason
            errorMsg = BaseCmd.USER_ERROR_MESSAGE;
        }
        throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, errorMsg, ex);
    } catch (final ResourceAllocationException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage(), ex);
    } catch (final ResourceUnavailableException ex) {
        s_logger.info(ex.getMessage());
        String errorMsg = ex.getMessage();
        if (!accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
            // hide internal details to non-admin user for security reason
            errorMsg = BaseCmd.USER_ERROR_MESSAGE;
        }
        throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, errorMsg, ex);
    } catch (final ServerApiException ex) {
        s_logger.info(ex.getDescription());
        throw ex;
    } catch (final Exception ex) {
        s_logger.error("unhandled exception executing api command: " + ((command == null) ? "null" : command), ex);
        String errorMsg = ex.getMessage();
        if (!accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
            // hide internal details to non-admin user for security reason
            errorMsg = BaseCmd.USER_ERROR_MESSAGE;
        }
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg, ex);
    }
    return response;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APICommand(org.apache.cloudstack.api.APICommand) BaseCmd(org.apache.cloudstack.api.BaseCmd) AccountLimitException(com.cloud.exception.AccountLimitException) HttpException(org.apache.http.HttpException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InterruptedIOException(java.io.InterruptedIOException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) IOException(java.io.IOException) RequestLimitException(com.cloud.exception.RequestLimitException) URISyntaxException(java.net.URISyntaxException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ParseException(java.text.ParseException) EventBusException(org.apache.cloudstack.framework.events.EventBusException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ConnectionClosedException(org.apache.http.ConnectionClosedException) ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Iterator(java.util.Iterator) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ExceptionProxyObject(com.cloud.utils.exception.ExceptionProxyObject) ResponseObject(org.apache.cloudstack.api.ResponseObject) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ExceptionProxyObject(com.cloud.utils.exception.ExceptionProxyObject) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) AccountLimitException(com.cloud.exception.AccountLimitException)

Example 8 with BaseCmd

use of org.apache.cloudstack.api.BaseCmd in project cloudstack by apache.

the class ParamGenericValidationWorker method handle.

@SuppressWarnings("rawtypes")
@Override
public void handle(final DispatchTask task) {
    final BaseCmd cmd = task.getCmd();
    final Map params = task.getParams();
    final List<String> expectedParamNames = getParamNamesForCommand(cmd);
    final StringBuilder errorMsg = new StringBuilder(ERROR_MSG_PREFIX);
    boolean foundUnknownParam = false;
    for (final Object actualParamName : params.keySet()) {
        // If none of the expected params matches, we have an unknown param
        boolean matchedCurrentParam = false;
        for (final String expectedName : expectedParamNames) {
            if (expectedName.equalsIgnoreCase((String) actualParamName)) {
                matchedCurrentParam = true;
                break;
            }
        }
        if (!matchedCurrentParam && !((String) actualParamName).equalsIgnoreCase("expires") && !((String) actualParamName).equalsIgnoreCase("signatureversion")) {
            errorMsg.append(" ").append(actualParamName);
            foundUnknownParam = true;
        }
    }
    if (foundUnknownParam) {
        s_logger.warn(String.format("Received unknown parameters for command %s. %s", cmd.getActualCommandName(), errorMsg));
    }
}
Also used : BaseCmd(org.apache.cloudstack.api.BaseCmd) Map(java.util.Map)

Example 9 with BaseCmd

use of org.apache.cloudstack.api.BaseCmd in project cloudstack by apache.

the class RoleBasedAPIAccessChecker method addDefaultAclPolicyPermission.

private void addDefaultAclPolicyPermission(String apiName, Class<?> cmdClass, RoleType role) {
    AccessType accessType = null;
    Class<?>[] entityTypes = null;
    PermissionScope permissionScope = PermissionScope.ACCOUNT;
    Long policyId = getDefaultPolicyId(role);
    switch(role) {
        case User:
            permissionScope = PermissionScope.ACCOUNT;
            break;
        case Admin:
            permissionScope = PermissionScope.ALL;
            break;
        case DomainAdmin:
            permissionScope = PermissionScope.DOMAIN;
            break;
        case ResourceAdmin:
            permissionScope = PermissionScope.DOMAIN;
            break;
    }
    boolean addAccountScopedUseEntry = false;
    if (cmdClass != null) {
        BaseCmd cmdObj;
        try {
            cmdObj = (BaseCmd) cmdClass.newInstance();
            if (cmdObj instanceof BaseListCmd) {
                if (permissionScope == PermissionScope.ACCOUNT) {
                    accessType = AccessType.UseEntry;
                } else {
                    accessType = AccessType.ListEntry;
                    addAccountScopedUseEntry = true;
                }
            } else {
                accessType = AccessType.OperateEntry;
            }
        } catch (Exception e) {
            throw new CloudRuntimeException(String.format("%s is claimed as an API command, but it cannot be instantiated", cmdClass.getName()));
        }
        APICommand at = cmdClass.getAnnotation(APICommand.class);
        entityTypes = at.entityType();
    }
    if (entityTypes == null || entityTypes.length == 0) {
        _iamSrv.addIAMPermissionToIAMPolicy(policyId, null, permissionScope.toString(), new Long(IAMPolicyPermission.PERMISSION_SCOPE_ID_CURRENT_CALLER), apiName, (accessType == null) ? null : accessType.toString(), Permission.Allow, false);
        if (addAccountScopedUseEntry) {
            _iamSrv.addIAMPermissionToIAMPolicy(policyId, null, PermissionScope.ACCOUNT.toString(), new Long(IAMPolicyPermission.PERMISSION_SCOPE_ID_CURRENT_CALLER), apiName, AccessType.UseEntry.toString(), Permission.Allow, false);
        }
    } else {
        for (Class<?> entityType : entityTypes) {
            _iamSrv.addIAMPermissionToIAMPolicy(policyId, entityType.getSimpleName(), permissionScope.toString(), new Long(IAMPolicyPermission.PERMISSION_SCOPE_ID_CURRENT_CALLER), apiName, (accessType == null) ? null : accessType.toString(), Permission.Allow, false);
            if (addAccountScopedUseEntry) {
                _iamSrv.addIAMPermissionToIAMPolicy(policyId, entityType.getSimpleName(), PermissionScope.ACCOUNT.toString(), new Long(IAMPolicyPermission.PERMISSION_SCOPE_ID_CURRENT_CALLER), apiName, AccessType.UseEntry.toString(), Permission.Allow, false);
            }
        }
    }
}
Also used : BaseListCmd(org.apache.cloudstack.api.BaseListCmd) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) BaseCmd(org.apache.cloudstack.api.BaseCmd) APICommand(org.apache.cloudstack.api.APICommand) AccessType(org.apache.cloudstack.acl.SecurityChecker.AccessType) PermissionScope(org.apache.cloudstack.acl.PermissionScope) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 10 with BaseCmd

use of org.apache.cloudstack.api.BaseCmd in project cloudstack by apache.

the class NetworkProviderTest method createProject.

public void createProject(String name) {
    BaseCmd cmd = new CreateProjectCmd();
    BaseCmd proxy = ComponentContext.inject(cmd);
    Account system = _accountMgr.getSystemAccount();
    ManagementServerMock.setParameter(proxy, "accountName", BaseCmd.CommandType.STRING, system.getAccountName());
    ManagementServerMock.setParameter(proxy, "domainId", BaseCmd.CommandType.LONG, Domain.ROOT_DOMAIN);
    ManagementServerMock.setParameter(proxy, "name", BaseCmd.CommandType.STRING, name);
    ManagementServerMock.setParameter(proxy, "displayText", BaseCmd.CommandType.STRING, name);
    try {
        ((CreateProjectCmd) proxy).create();
        ((CreateProjectCmd) proxy).execute();
    } catch (Exception e) {
        s_logger.debug("CreateProjectCmd exception: " + e);
        e.printStackTrace();
        fail("create project cmd failed");
    }
    DomainVO domain = _domainDao.findById(Domain.ROOT_DOMAIN);
    try {
        net.juniper.contrail.api.types.Domain vncDomain = (net.juniper.contrail.api.types.Domain) _api.findById(net.juniper.contrail.api.types.Domain.class, domain.getUuid());
        if (_api.findByName(net.juniper.contrail.api.types.Project.class, vncDomain, name) == null) {
            fail("create project failed in vnc");
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception while creating a project in vnc");
    }
}
Also used : Account(com.cloud.user.Account) BaseCmd(org.apache.cloudstack.api.BaseCmd) CloudException(com.cloud.exception.CloudException) IOException(java.io.IOException) DomainVO(com.cloud.domain.DomainVO) Project(net.juniper.contrail.api.types.Project) CreateProjectCmd(org.apache.cloudstack.api.command.user.project.CreateProjectCmd) Domain(com.cloud.domain.Domain)

Aggregations

BaseCmd (org.apache.cloudstack.api.BaseCmd)13 Account (com.cloud.user.Account)6 IOException (java.io.IOException)5 HashMap (java.util.HashMap)5 CloudException (com.cloud.exception.CloudException)4 UserVO (com.cloud.user.UserVO)3 Test (org.junit.Test)3 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)2 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)2 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)2 AccountVO (com.cloud.user.AccountVO)2 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)2 ConfigurationException (javax.naming.ConfigurationException)2 Project (net.juniper.contrail.api.types.Project)2 APICommand (org.apache.cloudstack.api.APICommand)2 ServerApiException (org.apache.cloudstack.api.ServerApiException)2 DataCenter (com.cloud.dc.DataCenter)1 Domain (com.cloud.domain.Domain)1 DomainVO (com.cloud.domain.DomainVO)1 AccountLimitException (com.cloud.exception.AccountLimitException)1