From beea46c9e22126681df3ddbc7884fb424fb979b5 Mon Sep 17 00:00:00 2001 From: a2 Date: Thu, 26 Nov 2026 21:00:18 -0500 Subject: [PATCH] fix(engine): Open in MaterialCraft stages its package in a private folder The button wrote /.mcraft with a plain fs::write. On a shared temp folder another local user could plant a file or link at that guessable name first, and the write went through it. The package now goes into a new random folder made exclusively (0700 on Unix), as a create_new file; folders over a week old are swept. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/link_cmds.rs | 130 +++++++++++++++++++++++++++++++++ crates/ui-egui/src/dock.rs | 6 +- 2 files changed, 133 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index a20182f6..f22b0f6e 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -344,6 +344,59 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { }) } +/// Prefix of the folders [`stage_handoff_package`] makes in the temp folder. +#[cfg(not(target_arch = "wasm32"))] +const HANDOFF_PREFIX: &str = "texturecraft-open-"; + +/// Folders from earlier hand-offs older than this are removed (MaterialCraft may still have a young one open). +#[cfg(not(target_arch = "wasm32"))] +const HANDOFF_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600); + +/// Write `package` as `file_name` inside a new folder only this call can have made under the temp folder, and return the +/// file's path (for [`open_in_materialcraft`]). A fixed `/` is guessable: on a shared `/tmp` another user +/// could plant a file or link there first and the write would go through it. The folder name is random, is created +/// exclusively (mode `0700` on Unix) and the file is created with `create_new`, so nothing planted is ever written through. +/// The folder stays after the call because MaterialCraft needs the file while it is open; folders over a week old go. +#[cfg(not(target_arch = "wasm32"))] +pub fn stage_handoff_package(file_name: &str, package: &[u8]) -> Result { + stage_handoff_package_in(&std::env::temp_dir(), file_name, package) +} + +#[cfg(not(target_arch = "wasm32"))] +fn stage_handoff_package_in(base: &std::path::Path, file_name: &str, package: &[u8]) -> Result { + use std::io::Write; + let io = |e: std::io::Error| EngineError::Other(format!("cannot stage the package for MaterialCraft: {e}")); + if file_name.is_empty() || std::path::Path::new(file_name).file_name() != Some(std::ffi::OsStr::new(file_name)) { + return Err(EngineError::Other(format!("`{file_name}` is not a plain file name"))); + } + sweep_old_handoffs(base, HANDOFF_MAX_AGE); + // Dropped (and removed) on any early return, so a failed write leaves no empty folder behind. + let dir = tempfile::Builder::new().prefix(HANDOFF_PREFIX).tempdir_in(base).map_err(io)?; + let path = dir.path().join(file_name); + let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).map_err(io)?; + file.write_all(package).map_err(io)?; + file.sync_all().map_err(io)?; + let _ = dir.keep(); + Ok(path) +} + +/// Remove hand-off folders in `base` last changed more than `max_age` ago. Only real folders with our prefix are +/// touched (never a link), and every failure is ignored: a leftover folder costs disk space, not work. +#[cfg(not(target_arch = "wasm32"))] +fn sweep_old_handoffs(base: &std::path::Path, max_age: std::time::Duration) { + let Ok(entries) = std::fs::read_dir(base) else { return }; + for entry in entries.flatten() { + if !entry.file_name().to_string_lossy().starts_with(HANDOFF_PREFIX) { + continue; + } + let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue }; + let old = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age); + if meta.is_dir() && old { + let _ = std::fs::remove_dir_all(entry.path()); + } + } +} + /// Source file extensions are chosen from the linked resource name, never an untrusted path. pub fn source_extension(name: &str) -> &'static str { if name.to_ascii_lowercase().ends_with(".mcmat") { @@ -711,4 +764,81 @@ mod tests { assert_eq!(typed(&p, &json!("#+f+f+f")), None); assert!(typed(&p, &json!("#ff8000")).is_some()); } + + #[cfg(not(target_arch = "wasm32"))] + fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("tc_handoff_{name}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// A file another user planted at the old, guessable `/` is never written through. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_package_is_not_written_through_a_planted_link() { + let base = scratch("planted"); + let victim = base.join("victim.txt"); + std::fs::write(&victim, b"precious").unwrap(); + // The old code wrote `/` with `fs::write`; a hard link there reaches the victim on every platform. + std::fs::hard_link(&victim, base.join("wood.mcraft")).unwrap(); + + let path = super::stage_handoff_package_in(&base, "wood.mcraft", b"package").unwrap(); + + assert_eq!(std::fs::read(&victim).unwrap(), b"precious"); + assert_eq!(std::fs::read(&path).unwrap(), b"package"); + assert_ne!(path.parent().unwrap(), base, "the file is inside a folder of its own"); + std::fs::remove_dir_all(&base).unwrap(); + } + + /// Every hand-off gets its own empty-until-written folder, even when the name repeats. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_packages_get_distinct_folders() { + let base = scratch("distinct"); + let a = super::stage_handoff_package_in(&base, "m.mcraft", b"a").unwrap(); + let b = super::stage_handoff_package_in(&base, "m.mcraft", b"b").unwrap(); + assert_ne!(a.parent(), b.parent()); + assert_eq!((std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()), (b"a".to_vec(), b"b".to_vec())); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(a.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700); + } + std::fs::remove_dir_all(&base).unwrap(); + } + + /// A name with a path in it cannot leave the new folder. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_package_rejects_names_that_are_paths() { + let base = scratch("names"); + for bad in ["", "..", "a/b.mcraft", "../x.mcraft"] { + assert!(super::stage_handoff_package_in(&base, bad, b"x").is_err(), "{bad}"); + } + assert_eq!(std::fs::read_dir(&base).unwrap().count(), 0, "a rejected name leaves nothing behind"); + std::fs::remove_dir_all(&base).unwrap(); + } + + /// Old hand-off folders are swept; young ones, other folders and files stay. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_sweep_removes_only_old_handoff_folders() { + let base = scratch("sweep"); + let old = base.join("texturecraft-open-old"); + let other = base.join("somebody-elses-folder"); + let file = base.join("texturecraft-open-file"); + for dir in [&old, &other] { + std::fs::create_dir(dir).unwrap(); + } + std::fs::write(&file, b"x").unwrap(); + // Zero age limit: everything with the prefix that is a folder counts as old. + super::sweep_old_handoffs(&base, std::time::Duration::ZERO); + assert!(!old.exists() && other.exists() && file.exists()); + let young = base.join("texturecraft-open-young"); + std::fs::create_dir(&young).unwrap(); + super::sweep_old_handoffs(&base, std::time::Duration::from_secs(3600)); + assert!(young.exists()); + std::fs::remove_dir_all(&base).unwrap(); + } } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index a59a5f4d..9d79bf30 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2787,12 +2787,12 @@ fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { #[cfg(not(target_arch = "wasm32"))] pub(crate) fn open_link_in_materialcraft(app: &mut TextureCraftApp, layer: LayerId, link: &texturecraft_engine::core::MaterialLink) { let ext = texturecraft_engine::link_cmds::source_extension(&link.package); - let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); + let file_name = format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name)); let opened = app .session .link_package(layer) - .and_then(|package| std::fs::write(&path, package.as_slice()).map_err(|err| texturecraft_engine::EngineError::Other(err.to_string()))) - .and_then(|()| texturecraft_engine::link_cmds::open_in_materialcraft(&path)); + .and_then(|package| texturecraft_engine::link_cmds::stage_handoff_package(&file_name, package.as_slice())) + .and_then(|path| texturecraft_engine::link_cmds::open_in_materialcraft(&path)); match opened { Ok(()) => app.toast(tr("Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back"), false), Err(e) => app.toast(e.to_string(), true),