diff --git a/server/src/main/java/com/cloud/api/ApiServer.java b/server/src/main/java/com/cloud/api/ApiServer.java index 083f4629740f..1b6bc367f83e 100644 --- a/server/src/main/java/com/cloud/api/ApiServer.java +++ b/server/src/main/java/com/cloud/api/ApiServer.java @@ -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 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 + ); + + @Override public boolean configure(final String name, final Map params) throws ConfigurationException { messageBus.subscribe(AsyncJob.Topics.JOB_EVENT_PUBLISH, MessageDispatcher.getDispatcher(this)); @@ -1770,7 +1783,8 @@ public ConfigKey[] getConfigKeys() { useForwardHeader, listOfForwardHeaders, ApiSessionKeyCookieSameSiteSetting, - ApiSessionKeyCheckLocations + ApiSessionKeyCheckLocations, + ApiDisallowInternalIds }; } } diff --git a/server/src/main/java/com/cloud/api/dispatch/ParamProcessWorker.java b/server/src/main/java/com/cloud/api/dispatch/ParamProcessWorker.java index e70c7aace344..d68abfc0e676 100644 --- a/server/src/main/java/com/cloud/api/dispatch/ParamProcessWorker.java +++ b/server/src/main/java/com/cloud/api/dispatch/ParamProcessWorker.java @@ -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; @@ -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) { 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; + } // 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) { diff --git a/server/src/test/java/com/cloud/api/dispatch/ParamProcessWorkerTest.java b/server/src/test/java/com/cloud/api/dispatch/ParamProcessWorkerTest.java index 81e14bcfe66f..83ba1e65ddea 100644 --- a/server/src/test/java/com/cloud/api/dispatch/ParamProcessWorkerTest.java +++ b/server/src/test/java/com/cloud/api/dispatch/ParamProcessWorkerTest.java @@ -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 { @@ -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 entities = new HashMap<>(); @@ -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 { @@ -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 params = new HashMap<>(); + params.put("legacyvmid", "5"); + paramProcessWorkerSpy.processParameters(new TestCmd(), params); + } }