fix(instance): harden config and shortcut persistence
This commit is contained in:
1 parent
a25f7d20c8
commit
9a408769c5
4 files changed
+141
-35
No files matched your search
+69
-19
@@ -45,7 +45,7 @@ pub fn icon_path() -> Option<PathBuf> {
|
||||
// lazily writes the bundled svg icon to disk the first time a shortcut needs it
|
||||
fn ensure_icon() -> Option<PathBuf> {
|
||||
let path = icon_path()?;
|
||||
if path.exists() {
|
||||
if std::fs::read(&path).ok().as_deref() == Some(ICON_BYTES) {
|
||||
return Some(path);
|
||||
}
|
||||
let parent = path.parent()?;
|
||||
@@ -53,7 +53,7 @@ fn ensure_icon() -> Option<PathBuf> {
|
||||
tracing::warn!("Failed to create icon directory: {}", e);
|
||||
return None;
|
||||
}
|
||||
if let Err(e) = std::fs::write(&path, ICON_BYTES) {
|
||||
if let Err(e) = crate::storage::write_atomic(&path, ICON_BYTES) {
|
||||
tracing::warn!("Failed to write bundled icon: {}", e);
|
||||
return None;
|
||||
}
|
||||
@@ -74,7 +74,9 @@ pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
|
||||
|
||||
let icon = ensure_icon();
|
||||
let content = build_content(&config.name, icon.as_deref());
|
||||
std::fs::write(&path, content)?;
|
||||
if std::fs::read_to_string(&path).ok().as_deref() != Some(content.as_str()) {
|
||||
crate::storage::write_atomic(&path, content.as_bytes())?;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
@@ -96,22 +98,28 @@ pub fn remove(name: &str) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn toggle(config: &InstanceConfig) -> std::io::Result<bool> {
|
||||
if exists(&config.name) {
|
||||
remove(&config.name)?;
|
||||
Ok(false)
|
||||
pub fn set_enabled(config: &InstanceConfig, enabled: bool) -> std::io::Result<()> {
|
||||
if enabled {
|
||||
create(config).map(|_| ())
|
||||
} else {
|
||||
create(config)?;
|
||||
Ok(true)
|
||||
remove(&config.name)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn toggle(config: &InstanceConfig) -> std::io::Result<bool> {
|
||||
let enabled = !exists(&config.name);
|
||||
set_enabled(config, enabled)?;
|
||||
Ok(enabled)
|
||||
}
|
||||
|
||||
pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()> {
|
||||
if !exists(old_name) {
|
||||
let Some(old_path) = desktop_path(old_name).filter(|path| path.exists()) else {
|
||||
return Ok(());
|
||||
}
|
||||
remove(old_name)?;
|
||||
};
|
||||
create(new_config)?;
|
||||
if desktop_path(&new_config.name).as_ref() != Some(&old_path) {
|
||||
std::fs::remove_file(old_path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -148,7 +156,10 @@ fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
|
||||
out.push_str("Type=Application\n");
|
||||
out.push_str(&format!("Name=Minecraft - {name}\n"));
|
||||
out.push_str(&format!("Comment=Launch {name} Minecraft instance\n"));
|
||||
out.push_str(&format!("Exec=rmcl instance launch \"{name}\"\n"));
|
||||
out.push_str(&format!(
|
||||
"Exec=rmcl instance launch {}\n",
|
||||
quote_desktop_exec_arg(name)
|
||||
));
|
||||
if let Some(icon) = icon {
|
||||
out.push_str(&format!("Icon={}\n", icon.display()));
|
||||
}
|
||||
@@ -159,14 +170,12 @@ fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn build_windows_shortcut(name: &str) -> String {
|
||||
let escaped_name = name.replace('"', "\"\"");
|
||||
let command = format!("rmcl instance launch {}", quote_windows_arg(name));
|
||||
let escaped_command = command.replace('"', "\"\"");
|
||||
|
||||
let mut out = String::new();
|
||||
out.push_str("Set shell = CreateObject(\"WScript.Shell\")\r\n");
|
||||
out.push_str(&format!(
|
||||
"shell.Run \"rmcl instance launch \"\"{}\"\"\", 0, False\r\n",
|
||||
escaped_name
|
||||
));
|
||||
out.push_str(&format!("shell.Run \"{escaped_command}\", 0, False\r\n"));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -175,10 +184,51 @@ fn build_macos_command(name: &str) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("#!/bin/bash\n");
|
||||
out.push_str(&format!("# Launch Minecraft instance: {name}\n"));
|
||||
out.push_str(&format!("rmcl instance launch \"{name}\"\n"));
|
||||
out.push_str(&format!("rmcl instance launch {}\n", quote_shell_arg(name)));
|
||||
out
|
||||
}
|
||||
|
||||
fn quote_desktop_exec_arg(value: &str) -> String {
|
||||
let mut escaped = String::with_capacity(value.len() + 2);
|
||||
escaped.push('"');
|
||||
for character in value.chars() {
|
||||
if matches!(character, '"' | '`' | '$' | '\\') {
|
||||
escaped.push('\\');
|
||||
}
|
||||
escaped.push(character);
|
||||
}
|
||||
escaped.push('"');
|
||||
escaped
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn quote_shell_arg(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
fn quote_windows_arg(value: &str) -> String {
|
||||
let mut quoted = String::with_capacity(value.len() + 2);
|
||||
quoted.push('"');
|
||||
let mut backslashes = 0;
|
||||
for character in value.chars() {
|
||||
if character == '\\' {
|
||||
backslashes += 1;
|
||||
} else if character == '"' {
|
||||
quoted.extend(std::iter::repeat_n('\\', backslashes * 2 + 1));
|
||||
quoted.push('"');
|
||||
backslashes = 0;
|
||||
} else {
|
||||
quoted.extend(std::iter::repeat_n('\\', backslashes));
|
||||
quoted.push(character);
|
||||
backslashes = 0;
|
||||
}
|
||||
}
|
||||
quoted.extend(std::iter::repeat_n('\\', backslashes * 2));
|
||||
quoted.push('"');
|
||||
quoted
|
||||
}
|
||||
|
||||
// replaces anything that isn't alphanumeric, dash, or underscore with _
|
||||
fn sanitize(name: &str) -> String {
|
||||
name.chars()
|
||||
|
||||
+27
-16
@@ -412,6 +412,7 @@ impl InstanceManager {
|
||||
}
|
||||
|
||||
pub fn delete(&self, name: &str) -> Result<(), InstanceError> {
|
||||
validate_name(name)?;
|
||||
let instance_dir = self.instances_dir.join(name);
|
||||
if !instance_dir.exists() {
|
||||
tracing::warn!(
|
||||
@@ -437,6 +438,7 @@ impl InstanceManager {
|
||||
}
|
||||
|
||||
pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> {
|
||||
validate_name(old_name)?;
|
||||
let new_name = new_name.trim();
|
||||
if new_name.is_empty() {
|
||||
tracing::warn!("Cannot rename instance '{}': new name is empty", old_name);
|
||||
@@ -471,6 +473,9 @@ impl InstanceManager {
|
||||
);
|
||||
return Err(InstanceError::AlreadyExists(new_name.to_string()));
|
||||
}
|
||||
let mut config = self.load_one(old_name)?;
|
||||
config.name = new_name.to_owned();
|
||||
let json = serde_json::to_vec_pretty(&config)?;
|
||||
tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name);
|
||||
if let Err(e) = std::fs::rename(&old_dir, &new_dir) {
|
||||
tracing::error!(
|
||||
@@ -483,21 +488,19 @@ impl InstanceManager {
|
||||
}
|
||||
|
||||
let config_path = new_dir.join("instance.json");
|
||||
if let Ok(data) = std::fs::read_to_string(&config_path)
|
||||
&& let Ok(mut config) = serde_json::from_str::<InstanceConfig>(&data)
|
||||
{
|
||||
config.name = new_name.to_string();
|
||||
if let Ok(json) = serde_json::to_string_pretty(&config) {
|
||||
let _ = std::fs::write(&config_path, json);
|
||||
if let Err(error) = crate::storage::write_atomic(&config_path, &json) {
|
||||
if let Err(rollback_error) = std::fs::rename(&new_dir, &old_dir) {
|
||||
tracing::error!(
|
||||
"Failed to roll back instance rename from {} to {}: {}",
|
||||
new_dir.display(),
|
||||
old_dir.display(),
|
||||
rollback_error
|
||||
);
|
||||
}
|
||||
if let Err(e) = crate::instance::desktop::rename(old_name, &config) {
|
||||
tracing::warn!("Failed to rename desktop shortcut: {}", e);
|
||||
}
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"Renamed instance directory but could not update config at {}",
|
||||
config_path.display()
|
||||
);
|
||||
return Err(error.into());
|
||||
}
|
||||
if let Err(e) = crate::instance::desktop::rename(old_name, &config) {
|
||||
tracing::warn!("Failed to rename desktop shortcut: {}", e);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -589,10 +592,14 @@ impl InstanceManager {
|
||||
}
|
||||
|
||||
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
|
||||
validate_name(&instance.name)?;
|
||||
let instance_dir = self.instances_dir.join(&instance.name);
|
||||
if !instance_dir.is_dir() {
|
||||
return Err(InstanceError::NotFound(instance.name.clone()));
|
||||
}
|
||||
let config_path = instance_dir.join("instance.json");
|
||||
let json = serde_json::to_string_pretty(instance)?;
|
||||
std::fs::write(&config_path, &json)?;
|
||||
crate::storage::write_atomic(&config_path, json.as_bytes())?;
|
||||
tracing::debug!(
|
||||
"Saved instance '{}' config to {}",
|
||||
instance.name,
|
||||
@@ -617,7 +624,11 @@ fn validate_name(name: &str) -> Result<(), InstanceError> {
|
||||
name
|
||||
)));
|
||||
}
|
||||
if name.contains('/') || name.contains('\\') || name.starts_with('.') {
|
||||
if name.contains('/')
|
||||
|| name.contains('\\')
|
||||
|| name.starts_with('.')
|
||||
|| name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(InstanceError::InvalidName(format!(
|
||||
"Name contains invalid characters: {:?}",
|
||||
name
|
||||
|
||||
@@ -31,3 +31,16 @@ fn build_content_linux_with_icon() {
|
||||
let content = build_content("TestPack", Some(&icon));
|
||||
assert!(content.contains("Icon=/tmp/icon.png"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortcut_arguments_escape_platform_metacharacters() {
|
||||
assert_eq!(
|
||||
quote_desktop_exec_arg("Pack \"$HOME`\\"),
|
||||
"\"Pack \\\"\\$HOME\\`\\\\\""
|
||||
);
|
||||
assert_eq!(quote_shell_arg("Pack 'quoted'"), "'Pack '\\''quoted'\\'''");
|
||||
assert_eq!(
|
||||
quote_windows_arg("Pack \\\"quoted"),
|
||||
"\"Pack \\\\\\\"quoted\""
|
||||
);
|
||||
}
|
||||
@@ -52,6 +52,7 @@ fn validate_name_rejects_empty_traversal_and_hidden() {
|
||||
assert!(validate_name("").is_err());
|
||||
assert!(validate_name("path/traversal").is_err());
|
||||
assert!(validate_name(".hidden").is_err());
|
||||
assert!(validate_name("line\nbreak").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -61,6 +62,23 @@ fn delete_missing_instance_returns_not_found() {
|
||||
assert!(matches!(result, Err(InstanceError::NotFound(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_rejects_path_traversal() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let instances = tmp.path().join("instances");
|
||||
let meta = tmp.path().join("meta");
|
||||
std::fs::create_dir_all(&instances).unwrap();
|
||||
std::fs::create_dir_all(&meta).unwrap();
|
||||
let manager = InstanceManager::new(instances, meta);
|
||||
let outside = tmp.path().join("outside-instance");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
|
||||
let result = manager.delete("../outside-instance");
|
||||
|
||||
assert!(matches!(result, Err(InstanceError::InvalidName(_))));
|
||||
assert!(outside.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_then_load_all_round_trips_config() {
|
||||
let (manager, tmp) = test_manager();
|
||||
@@ -169,6 +187,20 @@ fn rename_target_exists_errors() {
|
||||
assert!(matches!(err, InstanceError::AlreadyExists(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_with_invalid_source_is_rejected() {
|
||||
let (manager, _tmp) = test_manager();
|
||||
let err = manager.rename("../outside", "safe-name").unwrap_err();
|
||||
assert!(matches!(err, InstanceError::InvalidName(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_rejects_invalid_instance_name() {
|
||||
let (manager, _tmp) = test_manager();
|
||||
let err = manager.save(&dummy_config("../outside")).unwrap_err();
|
||||
assert!(matches!(err, InstanceError::InvalidName(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn touch_last_played_updates_field() {
|
||||
let (manager, tmp) = test_manager();
|
||||
|
||||
Reference in new issue
Block a user