use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class UserVmManagerTest method testMoveVmToUser2.
// Test Move VM b/w accounts where caller doesn't have access to the old or new account
@Test(expected = PermissionDeniedException.class)
public void testMoveVmToUser2() throws Exception {
AssignVMCmd cmd = new AssignVMCmd();
Class<?> _class = cmd.getClass();
Field virtualmachineIdField = _class.getDeclaredField("virtualMachineId");
virtualmachineIdField.setAccessible(true);
virtualmachineIdField.set(cmd, 1L);
Field accountNameField = _class.getDeclaredField("accountName");
accountNameField.setAccessible(true);
accountNameField.set(cmd, "account");
Field domainIdField = _class.getDeclaredField("domainId");
domainIdField.setAccessible(true);
domainIdField.set(cmd, 1L);
// caller is of type 0
Account caller = new AccountVO("testaccount", 1, "networkdomain", (short) 1, UUID.randomUUID().toString());
UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
Account oldAccount = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
Account newAccount = new AccountVO("testaccount", 1, "networkdomain", (short) 1, UUID.randomUUID().toString());
UserVmVO vm = new UserVmVO(10L, "test", "test", 1L, HypervisorType.Any, 1L, false, false, 1L, 1L, 1, 5L, "test", "test", 1L);
vm.setState(VirtualMachine.State.Stopped);
when(_vmDao.findById(anyLong())).thenReturn(vm);
when(_accountService.getActiveAccountById(anyLong())).thenReturn(oldAccount);
when(_accountMgr.finalizeOwner(any(Account.class), anyString(), anyLong(), anyLong())).thenReturn(newAccount);
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);
when(_accountMgr.isRootAdmin(anyLong())).thenReturn(true);
try {
_userVmMgr.moveVMToUser(cmd);
} finally {
CallContext.unregister();
}
}
use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class ApiServer method verifyRequest.
@Override
public boolean verifyRequest(final Map<String, Object[]> requestParameters, final Long userId) throws ServerApiException {
try {
String apiKey = null;
String secretKey = null;
String signature = null;
String unsignedRequest = null;
final String[] command = (String[]) requestParameters.get(ApiConstants.COMMAND);
if (command == null) {
s_logger.info("missing command, ignoring request...");
return false;
}
final String commandName = command[0];
// if userId not null, that mean that user is logged in
if (userId != null) {
final User user = ApiDBUtils.findUserById(userId);
try {
checkCommandAvailable(user, commandName);
} catch (final RequestLimitException ex) {
s_logger.debug(ex.getMessage());
throw new ServerApiException(ApiErrorCode.API_LIMIT_EXCEED, ex.getMessage());
} catch (final PermissionDeniedException ex) {
s_logger.debug("The user with id:" + userId + " is not allowed to request the API command or the API command does not exist: " + commandName);
throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The user is not allowed to request the API command or the API command does not exist");
}
return true;
} else {
// check against every available command to see if the command exists or not
if (!s_apiNameCmdClassMap.containsKey(commandName) && !commandName.equals("login") && !commandName.equals("logout")) {
s_logger.debug("The user with id:" + userId + " is not allowed to request the API command or the API command does not exist: " + commandName);
throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The user is not allowed to request the API command or the API command does not exist");
}
}
// - build a request string with sorted params, make sure it's all lowercase
// - sign the request, verify the signature is the same
final List<String> parameterNames = new ArrayList<String>();
for (final Object paramNameObj : requestParameters.keySet()) {
// put the name in a list that we'll sort later
parameterNames.add((String) paramNameObj);
}
Collections.sort(parameterNames);
String signatureVersion = null;
String expires = null;
for (final String paramName : parameterNames) {
// parameters come as name/value pairs in the form String/String[]
final String paramValue = ((String[]) requestParameters.get(paramName))[0];
if (ApiConstants.SIGNATURE.equalsIgnoreCase(paramName)) {
signature = paramValue;
} else {
if (ApiConstants.API_KEY.equalsIgnoreCase(paramName)) {
apiKey = paramValue;
} else if (ApiConstants.SIGNATURE_VERSION.equalsIgnoreCase(paramName)) {
signatureVersion = paramValue;
} else if (ApiConstants.EXPIRES.equalsIgnoreCase(paramName)) {
expires = paramValue;
}
if (unsignedRequest == null) {
unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, HttpUtils.UTF_8).replaceAll("\\+", "%20");
} else {
unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, HttpUtils.UTF_8).replaceAll("\\+", "%20");
}
}
}
// if api/secret key are passed to the parameters
if ((signature == null) || (apiKey == null)) {
s_logger.debug("Expired session, missing signature, or missing apiKey -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey);
// no signature, bad request
return false;
}
Date expiresTS = null;
// FIXME: Hard coded signature, why not have an enum
if ("3".equals(signatureVersion)) {
// New signature authentication. Check for expire parameter and its validity
if (expires == null) {
s_logger.debug("Missing Expires parameter -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey);
return false;
}
synchronized (DateFormatToUse) {
try {
expiresTS = DateFormatToUse.parse(expires);
} catch (final ParseException pe) {
s_logger.debug("Incorrect date format for Expires parameter", pe);
return false;
}
}
final Date now = new Date(System.currentTimeMillis());
if (expiresTS.before(now)) {
s_logger.debug("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey);
return false;
}
}
final TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
txn.close();
User user = null;
// verify there is a user with this api key
final Pair<User, Account> userAcctPair = accountMgr.findUserByApiKey(apiKey);
if (userAcctPair == null) {
s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey);
return false;
}
user = userAcctPair.first();
final Account account = userAcctPair.second();
if (user.getState() != Account.State.enabled || !account.getState().equals(Account.State.enabled)) {
s_logger.info("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() + "; accountState: " + account.getState());
return false;
}
try {
checkCommandAvailable(user, commandName);
} catch (final RequestLimitException ex) {
s_logger.debug(ex.getMessage());
throw new ServerApiException(ApiErrorCode.API_LIMIT_EXCEED, ex.getMessage());
} catch (final PermissionDeniedException ex) {
s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user");
throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist or it is not available for user with id:" + userId);
}
// verify secret key exists
secretKey = user.getSecretKey();
if (secretKey == null) {
s_logger.info("User does not have a secret key associated with the account -- ignoring request, username: " + user.getUsername());
return false;
}
unsignedRequest = unsignedRequest.toLowerCase();
final Mac mac = Mac.getInstance("HmacSHA1");
final SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(unsignedRequest.getBytes());
final byte[] encryptedBytes = mac.doFinal();
final String computedSignature = Base64.encodeBase64String(encryptedBytes);
final boolean equalSig = ConstantTimeComparator.compareStrings(signature, computedSignature);
if (!equalSig) {
s_logger.info("User signature: " + signature + " is not equaled to computed signature: " + computedSignature);
} else {
CallContext.register(user, account);
}
return equalSig;
} catch (final ServerApiException ex) {
throw ex;
} catch (final Exception ex) {
s_logger.error("unable to verify request signature");
}
return false;
}
use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class ApiResponseHelper method queryJobResult.
@Override
public AsyncJobResponse queryJobResult(QueryAsyncJobResultCmd cmd) {
Account caller = CallContext.current().getCallingAccount();
AsyncJob job = _entityMgr.findById(AsyncJob.class, cmd.getId());
if (job == null) {
throw new InvalidParameterValueException("Unable to find a job by id " + cmd.getId());
}
User userJobOwner = _accountMgr.getUserIncludingRemoved(job.getUserId());
Account jobOwner = _accountMgr.getAccount(userJobOwner.getAccountId());
//check permissions
if (_accountMgr.isNormalUser(caller.getId())) {
//regular user can see only jobs he owns
if (caller.getId() != jobOwner.getId()) {
throw new PermissionDeniedException("Account " + caller + " is not authorized to see job id=" + job.getId());
}
} else if (_accountMgr.isDomainAdmin(caller.getId())) {
_accountMgr.checkAccess(caller, null, true, jobOwner);
}
return createAsyncJobResponse(_jobMgr.queryJob(cmd.getId(), true));
}
use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class NetworkServiceImpl method createPhysicalNetwork.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true)
public PhysicalNetwork createPhysicalNetwork(final Long zoneId, final String vnetRange, final String networkSpeed, final List<String> isolationMethods, String broadcastDomainRangeStr, final Long domainId, final List<String> tags, final String name) {
// Check if zone exists
if (zoneId == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
if (Grouping.AllocationState.Enabled == zone.getAllocationState()) {
// TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
throw new PermissionDeniedException("Cannot create PhysicalNetwork since the Zone is currently enabled, zone Id: " + zoneId);
}
NetworkType zoneType = zone.getNetworkType();
if (zoneType == NetworkType.Basic) {
if (!_physicalNetworkDao.listByZone(zoneId).isEmpty()) {
// TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + ", there is a physical network already existing in this basic Zone");
}
}
if (tags != null && tags.size() > 1) {
throw new InvalidParameterException("Only one tag can be specified for a physical network at this time");
}
if (isolationMethods != null && isolationMethods.size() > 1) {
throw new InvalidParameterException("Only one isolationMethod can be specified for a physical network at this time");
}
if (vnetRange != null) {
// Verify zone type
if (zoneType == NetworkType.Basic || (zoneType == NetworkType.Advanced && zone.isSecurityGroupEnabled())) {
throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network, Security Group enabled: " + zone.isSecurityGroupEnabled());
}
}
BroadcastDomainRange broadcastDomainRange = null;
if (broadcastDomainRangeStr != null && !broadcastDomainRangeStr.isEmpty()) {
try {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr.toUpperCase());
} catch (IllegalArgumentException ex) {
throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}");
}
// in Acton release you can specify only Zone broadcastdomain type in Advance zone, and Pod in Basic
if (zoneType == NetworkType.Basic && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.POD) {
throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only");
} else if (zoneType == NetworkType.Advanced && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.ZONE) {
throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only");
}
}
if (broadcastDomainRange == null) {
if (zoneType == NetworkType.Basic) {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.POD;
} else {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.ZONE;
}
}
try {
final BroadcastDomainRange broadcastDomainRangeFinal = broadcastDomainRange;
return Transaction.execute(new TransactionCallback<PhysicalNetworkVO>() {
@Override
public PhysicalNetworkVO doInTransaction(TransactionStatus status) {
// Create the new physical network in the database
long id = _physicalNetworkDao.getNextInSequence(Long.class, "id");
PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRangeFinal, name);
pNetwork.setTags(tags);
pNetwork.setIsolationMethods(isolationMethods);
pNetwork = _physicalNetworkDao.persist(pNetwork);
// Add vnet entries for the new zone if zone type is Advanced
if (vnetRange != null) {
addOrRemoveVnets(vnetRange.split(","), pNetwork);
}
// add VirtualRouter as the default network service provider
addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId());
if (pNetwork.getIsolationMethods().contains("GRE"))
addDefaultOvsToPhysicalNetwork(pNetwork.getId());
// add security group provider to the physical network
addDefaultSecurityGroupProviderToPhysicalNetwork(pNetwork.getId());
// add VPCVirtualRouter as the defualt network service provider
addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId());
// add baremetal as the defualt network service provider
addDefaultBaremetalProvidersToPhysicalNetwork(pNetwork.getId());
//Add Internal Load Balancer element as a default network service provider
addDefaultInternalLbProviderToPhysicalNetwork(pNetwork.getId());
return pNetwork;
}
});
} catch (Exception ex) {
s_logger.warn("Exception: ", ex);
throw new CloudRuntimeException("Fail to create a physical network");
}
}
use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class CreateSnapshotCmd method getEntityOwnerId.
@Override
public long getEntityOwnerId() {
Volume volume = _entityMgr.findById(Volume.class, getVolumeId());
if (volume == null) {
throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId);
}
Account account = _accountService.getAccount(volume.getAccountId());
//Can create templates for enabled projects/accounts only
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
Project project = _projectService.findByProjectAccountId(volume.getAccountId());
if (project.getState() != Project.State.Active) {
throw new PermissionDeniedException("Can't add resources to the project id=" + project.getId() + " in state=" + project.getState() + " as it's no longer active");
}
} else if (account.getState() == Account.State.disabled) {
throw new PermissionDeniedException("The owner of template is disabled: " + account);
}
return volume.getAccountId();
}
Aggregations