use of org.apache.cloudstack.api.APICommand 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);
}
}
}
}
use of org.apache.cloudstack.api.APICommand in project cloudstack by apache.
the class ApiDiscoveryServiceImpl method cacheResponseMap.
protected Map<String, List<String>> cacheResponseMap(Set<Class<?>> cmdClasses) {
Map<String, List<String>> responseApiNameListMap = new HashMap<String, List<String>>();
for (Class<?> cmdClass : cmdClasses) {
APICommand apiCmdAnnotation = cmdClass.getAnnotation(APICommand.class);
if (apiCmdAnnotation == null) {
apiCmdAnnotation = cmdClass.getSuperclass().getAnnotation(APICommand.class);
}
if (apiCmdAnnotation == null || !apiCmdAnnotation.includeInApiDoc() || apiCmdAnnotation.name().isEmpty()) {
continue;
}
String apiName = apiCmdAnnotation.name();
if (s_logger.isTraceEnabled()) {
s_logger.trace("Found api: " + apiName);
}
ApiDiscoveryResponse response = getCmdRequestMap(cmdClass, apiCmdAnnotation);
String responseName = apiCmdAnnotation.responseObject().getName();
if (!responseName.contains("SuccessResponse")) {
if (!responseApiNameListMap.containsKey(responseName)) {
responseApiNameListMap.put(responseName, new ArrayList<String>());
}
responseApiNameListMap.get(responseName).add(apiName);
}
response.setRelated(responseName);
Field[] responseFields = apiCmdAnnotation.responseObject().getDeclaredFields();
for (Field responseField : responseFields) {
ApiResponseResponse responseResponse = getFieldResponseMap(responseField);
response.addApiResponse(responseResponse);
}
response.setObjectName("api");
s_apiNameDiscoveryResponseMap.put(apiName, response);
}
for (String apiName : s_apiNameDiscoveryResponseMap.keySet()) {
ApiDiscoveryResponse response = s_apiNameDiscoveryResponseMap.get(apiName);
Set<ApiParameterResponse> processedParams = new HashSet<ApiParameterResponse>();
for (ApiParameterResponse param : response.getParams()) {
if (responseApiNameListMap.containsKey(param.getRelated())) {
List<String> relatedApis = responseApiNameListMap.get(param.getRelated());
param.setRelated(StringUtils.join(relatedApis, ","));
} else {
param.setRelated(null);
}
processedParams.add(param);
}
response.setParams(processedParams);
if (responseApiNameListMap.containsKey(response.getRelated())) {
List<String> relatedApis = responseApiNameListMap.get(response.getRelated());
relatedApis.remove(apiName);
response.setRelated(StringUtils.join(relatedApis, ","));
} else {
response.setRelated(null);
}
s_apiNameDiscoveryResponseMap.put(apiName, response);
}
return responseApiNameListMap;
}
use of org.apache.cloudstack.api.APICommand 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;
}
Aggregations