Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion server/src/main/java/com/cloud/api/ApiServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,19 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer
, ConfigKey.Scope.Global, null, null, null, null, null, ConfigKey.Kind.Select,
EnumSet.allOf(ApiSessionKeyCheckOption.class).stream().map(Enum::toString).collect(Collectors.joining(", ")));

public static final ConfigKey<Boolean> ApiDisallowInternalIds = new ConfigKey<>(
ConfigKey.CATEGORY_ADVANCED,
Boolean.class,
"api.disallow.internal.ids",
"true",
"When true (default), only UUIDs are accepted as entity identifiers and requests passing internal database IDs "
+ "(or any other non-UUID value) for UUID parameters are rejected with a parameter error. "
+ "When false, legacy pre-3.x APIs also accept internal database IDs for backward compatibility.",
true,
ConfigKey.Scope.Global
);
Comment on lines +372 to +382


@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
messageBus.subscribe(AsyncJob.Topics.JOB_EVENT_PUBLISH, MessageDispatcher.getDispatcher(this));
Expand Down Expand Up @@ -1770,7 +1783,8 @@ public ConfigKey<?>[] getConfigKeys() {
useForwardHeader,
listOfForwardHeaders,
ApiSessionKeyCookieSameSiteSetting,
ApiSessionKeyCheckLocations
ApiSessionKeyCheckLocations,
ApiDisallowInternalIds
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import com.cloud.api.ApiServer;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
Expand Down Expand Up @@ -496,27 +497,36 @@ private Date messageDate(final Date date, final int hourOfDay, final int minute,
return cal.getTime();
}

private Long translateUuidToInternalId(final String uuid, final Parameter annotation) {
protected boolean isInternalIdDisallowed() {
return Boolean.TRUE.equals(ApiServer.ApiDisallowInternalIds.value());
}

protected Long translateUuidToInternalId(final String uuid, final Parameter annotation) {
Comment on lines +500 to +504
if (uuid.equals("-1")) {
// FIXME: This is to handle a lot of hardcoded special cases where -1 is sent
// APITODO: Find and get rid of all hardcoded params in API Cmds and service layer
return -1L;
}
Long internalId = null;
// If annotation's empty, the cmd existed before 3.x try conversion to long
final boolean isPre3x = annotation.since().isEmpty();
final boolean internalIdDisallowed = isInternalIdDisallowed();
// Internal IDs are only honoured for pre-3.x APIs (empty since) when not disallowed
final boolean internalIdAllowed = annotation.since().isEmpty() && !internalIdDisallowed;
// Match against Java's UUID regex to check if input is uuid string
final boolean isUuid = UuidUtils.isUuid(uuid);
// Enforce that it's uuid for newly added apis from version 3.x
if (!isPre3x && !isUuid)
if (!internalIdAllowed && !isUuid) {
if (internalIdDisallowed) {
throw new InvalidParameterValueException(String.format("Invalid parameter %s value=%s, a valid UUID is expected", annotation.name(), uuid));
}
// Legacy behaviour: non-UUID values for 3.x+ APIs are ignored
return null;
}
Comment on lines +516 to +522

// There may be multiple entities defined on the @EntityReference of a Response.class
// UUID CommandType would expect only one entityType, so use the first entityType
final Class<?>[] entities = annotation.entityType()[0].getAnnotation(EntityReference.class).value();

// Allow both uuid and internal id for pre3x apis
if (isPre3x && !isUuid) {
if (internalIdAllowed && !isUuid) {
try {
internalId = Long.parseLong(uuid);
} catch (final NumberFormatException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,22 @@
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.command.user.address.AssociateIPAddrCmd;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.acl.SecurityChecker;
import org.apache.cloudstack.context.CallContext;

import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.User;
import com.cloud.utils.db.EntityManager;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;

@RunWith(MockitoJUnitRunner.class)
public class ParamProcessWorkerTest {
Expand All @@ -74,6 +78,11 @@ public class ParamProcessWorkerTest {
@Mock
BaseCmd baseCmdMock;

@Mock
private EntityManager entityManagerMock;

private static final String VM_UUID = "0e4b5c1a-3b0f-4d7e-9f6a-2c1d8e7f9a10";

private Account[] owners = new Account[]{ownerAccountMock};

private Map<Object, SecurityChecker.AccessType> entities = new HashMap<>();
Expand All @@ -98,6 +107,12 @@ public static class TestCmd extends BaseCmd {
@Parameter(name = "mountOptions", type = CommandType.STRING, validations = {ApiArgValidator.SafeCommandOptions})
String mountOptions;

@Parameter(name = "legacyvmid", type = CommandType.UUID, entityType = UserVmResponse.class)
Long legacyVmId;

@Parameter(name = "vmid", type = CommandType.UUID, entityType = UserVmResponse.class, since = "4.0.0")
Long vmId;

@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
ResourceAllocationException, NetworkRuleConflictException {
Expand Down Expand Up @@ -252,4 +267,51 @@ public void checkCallerAccessToEntitiesTestChecksCallerAccessToResource() {

Mockito.verify(accountManagerMock).validateAccountHasAccessToResource(callingAccountMock, SecurityChecker.AccessType.UseEntry, vmInstanceVo);
}

private Parameter getParameterAnnotation(String fieldName) throws NoSuchFieldException {
return TestCmd.class.getDeclaredField(fieldName).getAnnotation(Parameter.class);
}

@Test(expected = InvalidParameterValueException.class)
public void translateUuidToInternalIdTestRejectsInternalIdForPre3xApiWhenDisallowed() throws Exception {
Mockito.doReturn(true).when(paramProcessWorkerSpy).isInternalIdDisallowed();
paramProcessWorkerSpy.translateUuidToInternalId("5", getParameterAnnotation("legacyVmId"));
}

@Test(expected = InvalidParameterValueException.class)
public void translateUuidToInternalIdTestRejectsNonUuidForPost3xApiWhenDisallowed() throws Exception {
Mockito.doReturn(true).when(paramProcessWorkerSpy).isInternalIdDisallowed();
paramProcessWorkerSpy.translateUuidToInternalId("5", getParameterAnnotation("vmId"));
}

@Test
public void translateUuidToInternalIdTestAcceptsInternalIdForPre3xApiWhenAllowed() throws Exception {
Mockito.doReturn(false).when(paramProcessWorkerSpy).isInternalIdDisallowed();
Long id = paramProcessWorkerSpy.translateUuidToInternalId("5", getParameterAnnotation("legacyVmId"));
Assert.assertEquals(Long.valueOf(5L), id);
}

@Test
public void translateUuidToInternalIdTestIgnoresNonUuidForPost3xApiWhenAllowed() throws Exception {
Mockito.doReturn(false).when(paramProcessWorkerSpy).isInternalIdDisallowed();
Assert.assertNull(paramProcessWorkerSpy.translateUuidToInternalId("5", getParameterAnnotation("vmId")));
}

@Test
public void translateUuidToInternalIdTestAcceptsUuidWhenDisallowed() throws Exception {
Mockito.doReturn(true).when(paramProcessWorkerSpy).isInternalIdDisallowed();
VMInstanceVO vmMock = Mockito.mock(VMInstanceVO.class);
Mockito.when(vmMock.getId()).thenReturn(5L);
Mockito.when(entityManagerMock.findByUuidIncludingRemoved(VirtualMachine.class, VM_UUID)).thenReturn(vmMock);
Long id = paramProcessWorkerSpy.translateUuidToInternalId(VM_UUID, getParameterAnnotation("legacyVmId"));
Assert.assertEquals(Long.valueOf(5L), id);
}

@Test(expected = ServerApiException.class)
public void processParametersTestRejectsInternalIdWhenDisallowed() {
Mockito.doReturn(true).when(paramProcessWorkerSpy).isInternalIdDisallowed();
final HashMap<String, String> params = new HashMap<>();
params.put("legacyvmid", "5");
paramProcessWorkerSpy.processParameters(new TestCmd(), params);
}
}
Loading