diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 1ac07e5..c269e9d 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -173,7 +173,12 @@ impl Headless { None => self.session.path.clone().ok_or_else(|| bad("the package has no file yet (new, or opened from another program): give a `path`"))?, }; - let files = file_cmds::save_files_at(&self.session, &path)?; + let destination = match &self.fs { + Filesystem::Workspace(workspace) => workspace.save_document_path(&path)?.to_string_lossy().into_owned(), + Filesystem::TrustedLocal => path.clone(), + Filesystem::Denied => return Err(bad("file access is not granted")), + }; + let files = file_cmds::save_files_at(&self.session, &destination)?; let bytes = if file_cmds::is_mcraft(&path) { let bytes = files.zip().map_err(|error| bad(error.to_string()))?; self.write(&path, &bytes)?; diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 1fabaa5..3ef9532 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -19,13 +19,16 @@ pub struct AuthorizedWorkspace { read: Option>, read_path: Option, write: Option>, + write_path: Option, } impl AuthorizedWorkspace { pub fn new(read_root: Option<&Path>, write_root: Option<&Path>) -> Result { let read = open_root(read_root, "read")?; let read_path = read_root.map(std::fs::canonicalize).transpose().map_err(|e| bad(e.to_string()))?; - Ok(Self { read, read_path, write: open_root(write_root, "write")? }) + let write = open_root(write_root, "write")?; + let write_path = write_root.map(std::fs::canonicalize).transpose().map_err(|e| bad(e.to_string()))?; + Ok(Self { read, read_path, write, write_path }) } /// Engine identities are absolute. Actual dependency reads still go through the directory capability. @@ -33,6 +36,36 @@ impl AuthorizedWorkspace { Ok(self.read_path.as_ref().ok_or_else(|| denied("read"))?.join(relative_path(path)?)) } + /// Absolute destination identity for rebasing links; writes still use the capability. + pub(crate) fn save_document_path(&self, path: &str) -> Result { + let relative = relative_path(path)?; + let root = self.write.as_ref().ok_or_else(|| denied("write"))?; + let parent = relative.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")); + // A permitted directory symlink can change the number of parent traversals + // needed by saved links. Resolve it inside the same write capability. + let mut ancestor = parent; + let mut suffix = PathBuf::new(); + let parent = loop { + match root.canonicalize(ancestor) { + Ok(resolved) => break resolved.join(&suffix), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + // Preserve save-to-new-directory behavior without creating anything + // before serialization. Do not treat a dangling symlink as missing. + match root.symlink_metadata(ancestor) { + Err(missing) if missing.kind() == std::io::ErrorKind::NotFound => {} + _ => return Err(file_error("resolve destination", path, error)), + } + let leaf = ancestor.file_name().ok_or_else(|| file_error("resolve destination", path, error))?; + suffix = Path::new(leaf).join(suffix); + ancestor = ancestor.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")); + } + Err(error) => return Err(file_error("resolve destination", path, error)), + } + }; + let leaf = relative.file_name().ok_or_else(|| bad("missing destination filename"))?; + Ok(self.write_path.as_ref().ok_or_else(|| denied("write"))?.join(parent).join(leaf)) + } + pub(crate) fn read_dependency(&self, path: &str) -> Option> { if path.starts_with("sbs://") { return materialcraft_engine::formats::sbs::library::read(path).ok(); @@ -45,7 +78,7 @@ impl AuthorizedWorkspace { pub fn read(&self, path: &str) -> Result, AutomationError> { let rel = relative_path(path)?; let root = self.read.as_ref().ok_or_else(|| denied("read"))?; - let file = root.open(&rel).map_err(|e| file_error("read", path, e))?; + let file = root.open_with(&rel, ®ular_read_options()).map_err(|e| file_error("read", path, e))?; let metadata = file.metadata().map_err(|e| file_error("read", path, e))?; if !metadata.is_file() { return Err(bad(format!("not a regular file: `{path}`"))); @@ -111,7 +144,7 @@ impl AuthorizedWorkspace { } } Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { - let file = root.open(&rel).map_err(|error| file_error("read", path, error))?; + let file = root.open_with(&rel, ®ular_read_options()).map_err(|error| file_error("read", path, error))?; let metadata = file.metadata().map_err(|error| file_error("read", path, error))?; if !metadata.is_file() || metadata.len() != bytes.len() as u64 { return Err(bad(format!("Resource filename collision: `{path}`"))); @@ -129,6 +162,18 @@ impl AuthorizedWorkspace { } } +// Keep capability-based resolution while preventing FIFO opens from waiting for a writer. +fn regular_read_options() -> OpenOptions { + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use cap_std::fs::OpenOptionsExt; + options.custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32); + } + options +} + fn open_root(path: Option<&Path>, authority: &str) -> Result>, AutomationError> { let Some(path) = path else { return Ok(None) }; if path.as_os_str().is_empty() { @@ -210,6 +255,32 @@ mod tests { (inside, outside, ws) } + #[cfg(unix)] + #[test] + fn capability_reads_and_resource_collisions_reject_fifos_without_a_writer() { + use std::os::unix::fs::OpenOptionsExt; + use std::time::Duration; + for collision in [false, true] { + let (inside, _, ws) = roots(if collision { "fifo-collision" } else { "fifo-read" }); + let path = inside.join("pipe"); + assert!(std::process::Command::new("mkfifo").arg(&path).status().unwrap().success()); + let (sender, receiver) = std::sync::mpsc::channel(); + let worker = std::thread::spawn(move || { + let result = if collision { ws.write_resource("pipe", b"x") } else { ws.read("pipe").map(|_| ()) }; + sender.send(result).unwrap(); + }); + let result = receiver.recv_timeout(Duration::from_secs(2)); + if result.is_err() { + // Release the regression's blocked read before failing the test. + let writer = std::fs::OpenOptions::new().write(true).custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32).open(&path).unwrap(); + drop(writer); + } + worker.join().unwrap(); + std::fs::remove_dir_all(inside.parent().unwrap()).unwrap(); + assert!(result.expect("FIFO open must not wait for a writer").is_err()); + } + } + #[test] fn reads_and_writes_stay_in_the_root() { let (inside, _, ws) = roots("valid"); diff --git a/crates/automation/tests/package_files.rs b/crates/automation/tests/package_files.rs index 9c2d2c3..ea5c38b 100644 --- a/crates/automation/tests/package_files.rs +++ b/crates/automation/tests/package_files.rs @@ -126,6 +126,34 @@ fn scoped_publication_resolves_linked_graphs_and_images_using_the_granted_read_r let (pkg, entry) = formats::material::read_material(&std::fs::read(output.join("surface.sbs.mcmat")).unwrap()).unwrap(); assert_eq!(pkg.graph(entry).unwrap().name, "Oak"); assert_eq!(pkg.graphs.len(), 2); + + // Saving under a different granted root rebases links from that actual + // destination, not from the process working directory or a relative path. + app.save(Some("saved.sbs")).unwrap(); + let xml = std::fs::read_to_string(output.join("saved.sbs")).unwrap(); + assert!(xml.contains("../input/parts/finish.sbs"), "{xml}"); + assert_eq!(app.session.path.as_deref(), Some("saved.sbs")); + let workspace = AuthorizedWorkspace::new(Some(&dir), Some(&output)).unwrap(); + let mut reopened = Headless::new(Session::new(Package::new("Empty")), Filesystem::Workspace(workspace)); + reopened.load("published/saved.sbs").unwrap(); + let helper_path = input.join("parts/finish.sbs").canonicalize().unwrap().to_string_lossy().into_owned(); + assert!(reopened.session.pkg.dependencies.contains_key(&helper_path)); + assert!(reopened.session.pkg.dependencies.values().any(|dependency| dependency.name == "Helpers")); + app.save(Some("new/sub/saved.sbs")).unwrap(); + let xml = std::fs::read_to_string(output.join("new/sub/saved.sbs")).unwrap(); + assert!(xml.contains("../../../input/parts/finish.sbs"), "{xml}"); + reopened.load("published/new/sub/saved.sbs").unwrap(); + assert!(reopened.session.pkg.dependencies.contains_key(&helper_path)); + #[cfg(unix)] + { + std::fs::create_dir_all(output.join("nested/deep")).unwrap(); + std::os::unix::fs::symlink("nested/deep", output.join("alias")).unwrap(); + app.save(Some("alias/new/linked.sbs")).unwrap(); + let xml = std::fs::read_to_string(output.join("nested/deep/new/linked.sbs")).unwrap(); + assert!(xml.contains("../../../../input/parts/finish.sbs"), "{xml}"); + reopened.load("published/nested/deep/new/linked.sbs").unwrap(); + assert!(reopened.session.pkg.dependencies.values().any(|dependency| dependency.name == "Helpers")); + } } else { assert!(result.is_err()); assert!(!output.join("missing.sbs.mcmat").exists());