You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by sh...@apache.org on 2026/08/18 13:55:40 UTC
(cloudstack) 06/23: api,server,kvm: improve backup repository mount handling
This is an automated email from the ASF dual-hosted git repository.
shwstppr pushed a commit to branch 4.22
in repository https://gitbox.apache.org/repos/asf/cloudstack.git
commit 56ad044865bc539231a27fcb459326674b0d1fa5
Author: Abhishek Kumar <ab...@gmail.com>
AuthorDate: Thu Jun 18 15:12:03 2026 +0530
api,server,kvm: improve backup repository mount handling
Improves handling of mount options for backup repository.
Signed-off-by: Abhishek Kumar <ab...@gmail.com>
Co-authored-by: Wei Zhou <we...@apache.org>
---
.../org/apache/cloudstack/api/ApiArgValidator.java | 73 +++++++++++-
.../backup/repository/AddBackupRepositoryCmd.java | 4 +-
.../repository/UpdateBackupRepositoryCmd.java | 8 +-
.../LibvirtRestoreBackupCommandWrapper.java | 127 ++++++++++++---------
.../LibvirtRestoreBackupCommandWrapperTest.java | 120 ++++++++++---------
.../com/cloud/api/dispatch/ParamProcessWorker.java | 6 +
.../cloud/api/dispatch/ParamProcessWorkerTest.java | 20 ++++
7 files changed, 246 insertions(+), 112 deletions(-)
diff --git a/api/src/main/java/org/apache/cloudstack/api/ApiArgValidator.java b/api/src/main/java/org/apache/cloudstack/api/ApiArgValidator.java
index 38047235273..b60549346bf 100644
--- a/api/src/main/java/org/apache/cloudstack/api/ApiArgValidator.java
+++ b/api/src/main/java/org/apache/cloudstack/api/ApiArgValidator.java
@@ -17,9 +17,18 @@
package org.apache.cloudstack.api;
+import java.util.Locale;
+import java.util.regex.Pattern;
+
+import org.apache.commons.lang3.StringUtils;
+
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.utils.UuidUtils;
+
public enum ApiArgValidator {
/**
- * Validates if the parameter is null or empty with the method {@link Strings#isNullOrEmpty(String)}.
+ * Validates if the parameter is null or empty with the method {@link StringUtils#isEmpty(CharSequence)}.
+ * Validation is currently done in the method ParamProcessWorker#validateNonEmptyString(String, String).
*/
NotNullOrEmpty,
@@ -29,7 +38,8 @@ public enum ApiArgValidator {
PositiveNumber,
/**
- * Validates if the parameter is an UUID with the method {@link UuidUtils#isUuid(String)}.
+ * Validates if the parameter is a UUID with the method {@link UuidUtils#isUuid(String)}.
+ * Validation is currently done in the method ParamProcessWorker#validateUuidString(String, String).
*/
UuidString,
@@ -37,4 +47,63 @@ public enum ApiArgValidator {
* Validates if the parameter is a valid RFC Compliance domain name.
*/
RFCComplianceDomainName,
+
+ /**
+ * Validates command option strings to avoid unsafe/code-like content.
+ */
+ SafeCommandOptions((param, annotation) -> {
+ if (BaseCmd.CommandType.STRING.equals(annotation.type())) {
+ validateSafeCommandOptions(param, annotation.name());
+ }
+ });
+
+ private static final Pattern SAFE_COMMAND_OPTIONS_PATTERN = Pattern.compile("^[A-Za-z0-9,._=:/+\\-\\s]*$");
+
+ private static final String[] UNSAFE_TOKENS = {
+ "$(", "`", "&&", "||", ";", "|", ">", "<"
+ };
+
+ private final ValidationRule rule;
+
+ ApiArgValidator() {
+ this(null);
+ }
+
+ ApiArgValidator(ValidationRule rule) {
+ this.rule = rule;
+ }
+
+ public void validate(final Object paramObj, final Parameter annotation) {
+ if (rule != null) {
+ rule.validate(paramObj, annotation);
+ }
+ }
+
+ private static void validateSafeCommandOptions(final Object param, final String argName) {
+ final String value = String.valueOf(param);
+ if (StringUtils.isBlank(value)) {
+ return;
+ }
+
+ if (!SAFE_COMMAND_OPTIONS_PATTERN.matcher(value).matches()) {
+ throwInvalidParameterValueException(argName, "contains unsupported or unsafe characters");
+ }
+
+ final String normalized = value.toLowerCase(Locale.ROOT);
+ for (String token : UNSAFE_TOKENS) {
+ if (normalized.contains(token)) {
+ throwInvalidParameterValueException(argName, "contains code-like or unsafe content");
+ }
+ }
+ }
+
+ private static void throwInvalidParameterValueException(final String argName, final String customMsg) {
+ throw new InvalidParameterValueException(String.format("Invalid value provided for API arg: %s%s", argName,
+ StringUtils.isBlank(customMsg) ? "" : " - " + customMsg));
+ }
+
+ @FunctionalInterface
+ interface ValidationRule {
+ void validate(Object paramObj, Parameter annotation);
+ }
}
diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java
index 7caa4ce710f..630bca4f26a 100644
--- a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java
+++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java
@@ -20,6 +20,7 @@ package org.apache.cloudstack.api.command.user.backup.repository;
import com.cloud.utils.StringUtils;
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiArgValidator;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
@@ -57,7 +58,8 @@ public class AddBackupRepositoryCmd extends BaseCmd {
@Parameter(name = ApiConstants.PROVIDER, type = CommandType.STRING, description = "backup repository provider")
private String provider;
- @Parameter(name = ApiConstants.MOUNT_OPTIONS, type = CommandType.STRING, description = "shared storage mount options")
+ @Parameter(name = ApiConstants.MOUNT_OPTIONS, type = CommandType.STRING, description = "shared storage mount options",
+ validations = {ApiArgValidator.SafeCommandOptions})
private String mountOptions;
@Parameter(name = ApiConstants.ZONE_ID,
diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/UpdateBackupRepositoryCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/UpdateBackupRepositoryCmd.java
index 5ffd79e497e..740936221b5 100644
--- a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/UpdateBackupRepositoryCmd.java
+++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/UpdateBackupRepositoryCmd.java
@@ -17,8 +17,11 @@
package org.apache.cloudstack.api.command.user.backup.repository;
+import javax.inject.Inject;
+
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiArgValidator;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
@@ -29,8 +32,6 @@ import org.apache.cloudstack.backup.BackupRepository;
import org.apache.cloudstack.backup.BackupRepositoryService;
import org.apache.cloudstack.context.CallContext;
-import javax.inject.Inject;
-
@APICommand(name = "updateBackupRepository",
description = "Update a backup repository",
responseObject = BackupRepositoryResponse.class, since = "4.22.0",
@@ -53,7 +54,8 @@ public class UpdateBackupRepositoryCmd extends BaseCmd {
@Parameter(name = ApiConstants.ADDRESS, type = CommandType.STRING, description = "address of the backup repository")
private String address;
- @Parameter(name = ApiConstants.MOUNT_OPTIONS, type = CommandType.STRING, description = "shared storage mount options")
+ @Parameter(name = ApiConstants.MOUNT_OPTIONS, type = CommandType.STRING, description = "shared storage mount options",
+ validations = {ApiArgValidator.SafeCommandOptions})
private String mountOptions;
@Parameter(name = ApiConstants.CROSS_ZONE_INSTANCE_CREATION, type = CommandType.BOOLEAN, description = "backups in this repository can be used to create Instances on all Zones")
diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java
index 22dbfbdd67a..9ebb180b055 100644
--- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java
@@ -19,6 +19,26 @@
package com.cloud.hypervisor.kvm.resource.wrapper;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Objects;
+
+import org.apache.cloudstack.backup.BackupAnswer;
+import org.apache.cloudstack.backup.RestoreBackupCommand;
+import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
+import org.apache.cloudstack.utils.qemu.QemuImg;
+import org.apache.cloudstack.utils.qemu.QemuImgException;
+import org.apache.cloudstack.utils.qemu.QemuImgFile;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.libvirt.LibvirtException;
+
import com.cloud.agent.api.Answer;
import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
@@ -31,35 +51,11 @@ import com.cloud.utils.Pair;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.cloud.vm.VirtualMachine;
-import org.apache.cloudstack.backup.BackupAnswer;
-import org.apache.cloudstack.backup.RestoreBackupCommand;
-import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
-import org.apache.cloudstack.utils.qemu.QemuImg;
-import org.apache.cloudstack.utils.qemu.QemuImgException;
-import org.apache.cloudstack.utils.qemu.QemuImgFile;
-import org.apache.commons.lang3.RandomStringUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.libvirt.LibvirtException;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.Locale;
-import java.util.Objects;
@ResourceWrapper(handles = RestoreBackupCommand.class)
public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper<RestoreBackupCommand, Answer, LibvirtComputingResource> {
private static final String BACKUP_TEMP_FILE_PREFIX = "csbackup";
- private static final String MOUNT_COMMAND = "sudo mount -t %s %s %s";
- private static final String UMOUNT_COMMAND = "sudo umount %s";
private static final String FILE_PATH_PLACEHOLDER = "%s/%s";
- private static final String ATTACH_QCOW2_DISK_COMMAND = " virsh attach-disk %s %s %s --driver qemu --subdriver qcow2 --cache none";
- private static final String ATTACH_RAW_DISK_COMMAND = " virsh attach-disk %s %s %s --driver qemu --cache none";
- private static final String ATTACH_RBD_DISK_XML_COMMAND = " virsh attach-device %s /dev/stdin <<EOF%sEOF";
- private static final String CURRRENT_DEVICE = "virsh domblklist --domain %s | tail -n 3 | head -n 1 | awk '{print $1}'";
- private static final String RSYNC_COMMAND = "rsync -az %s %s";
private String getVolumeUuidFromPath(String volumePath, PrimaryDataStoreTO volumePool) {
if (Storage.StoragePoolType.Linstor.equals(volumePool.getPoolType())) {
@@ -205,32 +201,41 @@ public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper<RestoreBa
logger.error("Failed to create the tmp mount directory {} for restore", mountDirectory, e);
throw new CloudRuntimeException("Failed to create the tmp mount directory for restore on the KVM host");
}
-
- String mount = String.format(MOUNT_COMMAND, backupRepoType, backupRepoAddress, mountDirectory);
- if ("cifs".equals(backupRepoType)) {
- if (Objects.isNull(mountOptions) || mountOptions.trim().isEmpty()) {
- mountOptions = "nobrl";
- } else {
- mountOptions += ",nobrl";
+ try {
+ String mountPath = Script.getExecutableAbsolutePath("mount");
+ List<String> mountCmd = new ArrayList<>();
+ mountCmd.add("sudo");
+ mountCmd.add(mountPath);
+ mountCmd.add("-t");
+ mountCmd.add(backupRepoType);
+ mountCmd.add(backupRepoAddress);
+ mountCmd.add(mountDirectory);
+ if ("cifs".equals(backupRepoType)) {
+ if (StringUtils.isBlank(mountOptions)) {
+ mountOptions = "nobrl";
+ } else {
+ mountOptions += ",nobrl";
+ }
}
- }
- if (Objects.nonNull(mountOptions) && !mountOptions.trim().isEmpty()) {
- mount += " -o " + mountOptions;
- }
-
- int exitValue = Script.runSimpleBashScriptForExitValue(mount, mountTimeout, false);
- if (exitValue != 0) {
- logger.error("Failed to mount repository {} of type {} to the directory {}", backupRepoAddress, backupRepoType, mountDirectory);
+ if (StringUtils.isNotBlank(mountOptions)) {
+ mountCmd.add("-o");
+ mountCmd.add(mountOptions);
+ }
+ Script.executeCommand(mountCmd.toArray(new String[0]));
+ } catch (Exception e) {
+ logger.error("Failed to mount repository {} of type {} to the directory {}", backupRepoAddress, backupRepoType, mountDirectory, e);
throw new CloudRuntimeException("Failed to mount the backup repository on the KVM host");
}
return mountDirectory;
}
private void unmountBackupDirectory(String backupDirectory) {
- String umountCmd = String.format(UMOUNT_COMMAND, backupDirectory);
- int exitValue = Script.runSimpleBashScriptForExitValue(umountCmd);
- if (exitValue != 0) {
- logger.error("Failed to unmount backup directory {}", backupDirectory);
+ try {
+ String umountPath = Script.getExecutableAbsolutePath("umount");
+ String[] umountCmd = new String[] { "sudo", umountPath, backupDirectory };
+ Script.executeCommand(umountCmd);
+ } catch (Exception e) {
+ logger.error("Failed to unmount backup directory {}", backupDirectory, e);
throw new CloudRuntimeException("Failed to unmount the backup directory");
}
}
@@ -270,7 +275,8 @@ public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper<RestoreBa
return replaceBlockDeviceWithBackup(storagePoolMgr, volumePool, volumePath, backupPath, timeout, createTargetVolume, size);
}
- int exitValue = Script.runSimpleBashScriptForExitValue(String.format(RSYNC_COMMAND, backupPath, volumePath), timeout, false);
+ String[] rsyncCmd = new String[] { Script.getExecutableAbsolutePath("rsync"), "-az", backupPath, volumePath };
+ int exitValue = Script.executeCommandForExitValue(rsyncCmd);
return exitValue == 0;
}
@@ -313,8 +319,8 @@ public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper<RestoreBa
destVolume = volumePath;
break;
case RBD:
- destVolume = KVMPhysicalDisk.RBDStringBuilder(volumeStoragePool, volumePath);
- break;
+ destVolume = KVMPhysicalDisk.RBDStringBuilder(volumeStoragePool, volumePath);
+ break;
default:
throw new CloudRuntimeException(String.format("Unsupported storage pool type [%s] for block device restore with backup.", volumePool.getPoolType()));
}
@@ -334,21 +340,38 @@ public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper<RestoreBa
private boolean attachVolumeToVm(KVMStoragePoolManager storagePoolMgr, String vmName, PrimaryDataStoreTO volumePool, String volumePath) {
String deviceToAttachDiskTo = getDeviceToAttachDisk(vmName);
- int exitValue;
+ List<String> virshCmd = new ArrayList<>();
+ virshCmd.add(Script.getExecutableAbsolutePath("virsh"));
if (volumePool.getPoolType() == Storage.StoragePoolType.RBD) {
String xmlForRbdDisk = getXmlForRbdDisk(storagePoolMgr, volumePool, volumePath, deviceToAttachDiskTo);
logger.debug("RBD disk xml to attach: {}", xmlForRbdDisk);
- exitValue = Script.runSimpleBashScriptForExitValue(String.format(ATTACH_RBD_DISK_XML_COMMAND, vmName, xmlForRbdDisk));
- } else if (volumePool.getPoolType() == Storage.StoragePoolType.Linstor) {
- exitValue = Script.runSimpleBashScriptForExitValue(String.format(ATTACH_RAW_DISK_COMMAND, vmName, volumePath, deviceToAttachDiskTo));
+ virshCmd.add("attach-device");
+ virshCmd.add(vmName);
+ virshCmd.add("/dev/stdin");
+ virshCmd.add("<<EOF%sEOF");
} else {
- exitValue = Script.runSimpleBashScriptForExitValue(String.format(ATTACH_QCOW2_DISK_COMMAND, vmName, volumePath, deviceToAttachDiskTo));
+ virshCmd.add("attach-disk");
+ virshCmd.add(vmName);
+ virshCmd.add(volumePath);
+ virshCmd.add(deviceToAttachDiskTo);
+ if (Storage.StoragePoolType.Linstor.equals(volumePool.getPoolType())) {
+ virshCmd.add("--subdriver");
+ virshCmd.add("qcow2");
+ }
+ virshCmd.add("--cache");
+ virshCmd.add("none");
}
+ int exitValue = Script.executeCommandForExitValue(virshCmd.toArray(new String[0]));
return exitValue == 0;
}
private String getDeviceToAttachDisk(String vmName) {
- String currentDevice = Script.runSimpleBashScript(String.format(CURRRENT_DEVICE, vmName));
+ String[] domblkCmd = new String[] { Script.getExecutableAbsolutePath("virsh"), "domblklist", "--domain", vmName };
+ String[] tailCmd = new String[] { Script.getExecutableAbsolutePath("tail"), "-n", "3" };
+ String[] headCmd = new String[] { Script.getExecutableAbsolutePath("head"), "-n", "1" };
+ String[] awkCmd = new String[] { Script.getExecutableAbsolutePath("awk"), "'{print $1}'" };
+ Pair<Integer, String> result = Script.executePipedCommands(Arrays.asList(domblkCmd, tailCmd, headCmd, awkCmd), 0);
+ String currentDevice = result.second();
char lastChar = currentDevice.charAt(currentDevice.length() - 1);
char incrementedChar = (char) (lastChar + 1);
return currentDevice.substring(0, currentDevice.length() - 1) + incrementedChar;
diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapperTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapperTest.java
index ef6b5c08189..f028035e8dc 100644
--- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapperTest.java
+++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapperTest.java
@@ -16,11 +16,19 @@
// under the License.
package com.cloud.hypervisor.kvm.resource.wrapper;
-import com.cloud.agent.api.Answer;
-import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
-import com.cloud.storage.Storage;
-import com.cloud.utils.script.Script;
-import com.cloud.vm.VirtualMachine;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.lenient;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+
import org.apache.cloudstack.backup.BackupAnswer;
import org.apache.cloudstack.backup.RestoreBackupCommand;
import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
@@ -32,17 +40,12 @@ import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Arrays;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.lenient;
-import static org.mockito.Mockito.mockStatic;
-import static org.mockito.Mockito.when;
+import com.cloud.agent.api.Answer;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.storage.Storage;
+import com.cloud.utils.Pair;
+import com.cloud.utils.script.Script;
+import com.cloud.vm.VirtualMachine;
@RunWith(MockitoJUnitRunner.class)
public class LibvirtRestoreBackupCommandWrapperTest {
@@ -83,12 +86,16 @@ public class LibvirtRestoreBackupCommandWrapperTest {
filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath);
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString(), anyInt(), any(Boolean.class)))
- .thenReturn(0); // Mount success
+ scriptMock.when(() -> Script.getExecutableAbsolutePath(anyString()))
+ .thenAnswer(invocation -> invocation.getArgument(0));
+ scriptMock.when(() -> Script.executeCommand(any(String[].class)))
+ .thenReturn(null);
+ scriptMock.when(() -> Script.executeCommandForExitValue(any(String[].class)))
+ .thenReturn(0);
scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString()))
.thenReturn(0); // Other commands success
- scriptMock.when(() -> Script.runSimpleBashScript(anyString()))
- .thenReturn("vda"); // Current device
+ scriptMock.when(() -> Script.executePipedCommands(anyList(), anyLong()))
+ .thenReturn(new Pair<>(0, "vda"));
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);
@@ -126,8 +133,10 @@ public class LibvirtRestoreBackupCommandWrapperTest {
filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath);
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString(), anyInt(), any(Boolean.class)))
- .thenReturn(0); // Mount success
+ scriptMock.when(() -> Script.executeCommand(any(String[].class)))
+ .thenReturn(null);
+ scriptMock.when(() -> Script.executeCommandForExitValue(any(String[].class)))
+ .thenReturn(0);
scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString()))
.thenReturn(0); // Other commands success
@@ -165,8 +174,10 @@ public class LibvirtRestoreBackupCommandWrapperTest {
filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath);
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString(), anyInt(), any(Boolean.class)))
- .thenReturn(0); // Mount success
+ scriptMock.when(() -> Script.executeCommand(any(String[].class)))
+ .thenReturn(null);
+ scriptMock.when(() -> Script.executeCommandForExitValue(any(String[].class)))
+ .thenReturn(0);
scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString()))
.thenReturn(0); // Other commands success
@@ -207,12 +218,11 @@ public class LibvirtRestoreBackupCommandWrapperTest {
filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath);
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString(), anyInt(), any(Boolean.class)))
- .thenReturn(0); // Mount success
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString()))
- .thenReturn(0); // Other commands success
- scriptMock.when(() -> Script.runSimpleBashScript(anyString()))
- .thenReturn("vda"); // Current device
+ scriptMock.when(() -> Script.getExecutableAbsolutePath(Mockito.anyString()))
+ .thenAnswer(invocation -> invocation.getArgument(0));
+ scriptMock.when(() ->
+ Script.executePipedCommands(anyList(), anyLong()))
+ .thenReturn(new Pair<>(0, "vda")); // Current device
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);
@@ -251,8 +261,8 @@ public class LibvirtRestoreBackupCommandWrapperTest {
filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath);
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString(), anyInt(), any(Boolean.class)))
- .thenReturn(1); // Mount failure
+ scriptMock.when(() -> Script.executeCommand(any(String[].class)))
+ .thenThrow(new RuntimeException("failure")); // Mount failure
Answer result = wrapper.execute(command, libvirtComputingResource);
@@ -290,8 +300,8 @@ public class LibvirtRestoreBackupCommandWrapperTest {
filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath);
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString(), anyInt(), any(Boolean.class)))
- .thenReturn(0); // Mount success
+ scriptMock.when(() -> Script.executeCommand(any(String[].class)))
+ .thenReturn(null);
scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString()))
.thenAnswer(invocation -> {
String command = invocation.getArgument(0);
@@ -339,8 +349,8 @@ public class LibvirtRestoreBackupCommandWrapperTest {
filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath);
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString(), anyInt(), any(Boolean.class)))
- .thenReturn(0); // Mount success
+ scriptMock.when(() -> Script.executeCommand(any(String[].class)))
+ .thenReturn(null);
scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString()))
.thenAnswer(invocation -> {
String command = invocation.getArgument(0);
@@ -390,15 +400,16 @@ public class LibvirtRestoreBackupCommandWrapperTest {
filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath);
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString(), anyInt(), any(Boolean.class)))
+ scriptMock.when(() -> Script.getExecutableAbsolutePath(anyString()))
+ .thenAnswer(invocation -> invocation.getArgument(0));
+ scriptMock.when(() -> Script.executeCommand(any(String[].class)))
+ .thenReturn(null);
+ scriptMock.when(() -> Script.executeCommandForExitValue(any(String[].class)))
.thenAnswer(invocation -> {
- String command = invocation.getArgument(0);
- if (command.contains("mount")) {
- return 0; // mount success
- } else if (command.contains("rsync")) {
+ if (Arrays.stream(invocation.getArguments()).map(String::valueOf).anyMatch("rsync"::equals)) {
return 1; // Rsync failure
}
- return 0; // Other commands success
+ return 0;
});
scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString()))
.thenAnswer(invocation -> {
@@ -449,15 +460,16 @@ public class LibvirtRestoreBackupCommandWrapperTest {
filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath);
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString(), anyInt(), any(Boolean.class)))
+ scriptMock.when(() -> Script.getExecutableAbsolutePath(anyString()))
+ .thenAnswer(invocation -> invocation.getArgument(0));
+ scriptMock.when(() -> Script.executeCommand(any(String[].class)))
+ .thenReturn(null);
+ scriptMock.when(() -> Script.executeCommandForExitValue(any(String[].class)))
.thenAnswer(invocation -> {
- String command = invocation.getArgument(0);
- if (command.contains("mount")) {
- return 0; // Mount success
- } else if (command.contains("rsync")) {
- return 0; // Rsync success
+ if (Arrays.stream(invocation.getArguments()).map(String::valueOf).anyMatch("attach-disk"::equals)) {
+ return 1; // Attach failure
}
- return 0; // Other commands success
+ return 0;
});
scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString()))
.thenAnswer(invocation -> {
@@ -466,13 +478,11 @@ public class LibvirtRestoreBackupCommandWrapperTest {
return 0; // File exists
} else if (command.contains("qemu-img check")) {
return 0; // File is valid
- } else if (command.contains("virsh attach-disk")) {
- return 1; // Attach failure
}
return 0; // Other commands success
});
- scriptMock.when(() -> Script.runSimpleBashScript(anyString()))
- .thenReturn("vda"); // Current device
+ scriptMock.when(() -> Script.executePipedCommands(anyList(), anyLong()))
+ .thenReturn(new Pair<>(0, "vda"));
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);
@@ -553,7 +563,9 @@ public class LibvirtRestoreBackupCommandWrapperTest {
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString()))
.thenReturn(0); // All commands success
- scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString(), anyInt(), any(Boolean.class)))
+ scriptMock.when(() -> Script.executeCommand(any(String[].class)))
+ .thenReturn(null);
+ scriptMock.when(() -> Script.executeCommandForExitValue(any(String[].class)))
.thenReturn(0); // All commands success
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);
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 c4145755b56..8592d1a9fef 100644
--- a/server/src/main/java/com/cloud/api/dispatch/ParamProcessWorker.java
+++ b/server/src/main/java/com/cloud/api/dispatch/ParamProcessWorker.java
@@ -173,6 +173,12 @@ public class ParamProcessWorker implements DispatchWorker {
validateNameForRFCCompliance(paramObj, argName);
break;
}
+ break;
+ case SafeCommandOptions:
+ validator.validate(paramObj, annotation);
+ break;
+ default:
+ break;
}
}
}
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 a998d2e9ab4..81e14bcfe66 100644
--- a/server/src/test/java/com/cloud/api/dispatch/ParamProcessWorkerTest.java
+++ b/server/src/test/java/com/cloud/api/dispatch/ParamProcessWorkerTest.java
@@ -95,6 +95,9 @@ public class ParamProcessWorkerTest {
@Parameter(name = "vmHostNameParam", type = CommandType.STRING, validations = {ApiArgValidator.RFCComplianceDomainName})
String vmHostNameParam;
+ @Parameter(name = "mountOptions", type = CommandType.STRING, validations = {ApiArgValidator.SafeCommandOptions})
+ String mountOptions;
+
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
ResourceAllocationException, NetworkRuleConflictException {
@@ -139,6 +142,23 @@ public class ParamProcessWorkerTest {
Assert.assertEquals("test-host-name-123", cmd.vmHostNameParam);
}
+ @Test
+ public void processMountOptionsParameter_Valid() {
+ final HashMap<String, String> params = new HashMap<String, String>();
+ params.put("mountOptions", "vers=4.1,soft,timeo=600,retrans=2");
+ final TestCmd cmd = new TestCmd();
+ paramProcessWorkerSpy.processParameters(cmd, params);
+ Assert.assertEquals("vers=4.1,soft,timeo=600,retrans=2", cmd.mountOptions);
+ }
+
+ @Test(expected = ServerApiException.class)
+ public void processMountOptionsParameter_RejectCodeLikeContent() {
+ final HashMap<String, String> params = new HashMap<String, String>();
+ params.put("mountOptions", "rw;rm -rf /");
+ final TestCmd cmd = new TestCmd();
+ paramProcessWorkerSpy.processParameters(cmd, params);
+ }
+
@Test(expected = ServerApiException.class)
public void processVmHostNameParameter_CannotStartWithDigit() {
final HashMap<String, String> params = new HashMap<String, String>();