//! Copying host config into the guest share without following symlinks out of it. use anyhow::{Result, anyhow}; use std::fs; use std::path::{Path, PathBuf}; pub const STAGE_LIMIT: u64 = 256 << 20; /// Copy config into the stage, resolving symlinks (they'd dangle in the VM) but only when they /// resolve inside `roots`; no cycles, regular files and dirs only (a FIFO would hang fs::copy). pub fn copy_tree(src: &Path, dst: &Path, roots: &[PathBuf], budget: &mut u64, seen: &mut std::collections::HashSet) -> Result<()> { let Ok(real) = fs::canonicalize(src) else { return Ok(()) }; // dangling symlink if !roots.iter().any(|r| real.starts_with(r)) { eprintln!("wsbx: not sharing {} -> {} (outside the shared config)", src.display(), real.display()); return Ok(()); } let m = fs::metadata(&real)?; if m.is_dir() { if !seen.insert(real.clone()) { return Ok(()); // symlink cycle or already copied } fs::create_dir_all(dst)?; for e in fs::read_dir(&real)? { let e = e?; copy_tree(&e.path(), &dst.join(e.file_name()), roots, budget, seen)?; } } else if m.is_file() { *budget = budget.checked_sub(m.len()).ok_or_else(|| anyhow!("shared config exceeds {} MB", STAGE_LIMIT >> 20))?; fs::copy(&real, dst)?; } Ok(()) } #[cfg(test)] mod tests { #[test] fn copy_tree_contains_symlinks() { use std::os::unix::fs::symlink; let t = std::env::temp_dir().join(format!("wsbx-ct-{}", std::process::id())); let (root, out, secret) = (t.join("root"), t.join("out"), t.join("secret")); std::fs::create_dir_all(root.join("skills/a")).unwrap(); std::fs::create_dir_all(&secret).unwrap(); std::fs::write(root.join("skills/a/SKILL.md"), "ok").unwrap(); std::fs::write(secret.join("id_rsa"), "key").unwrap(); symlink(&secret, root.join("skills/leak")).unwrap(); // escapes the root symlink(root.join("skills"), root.join("skills/a/loop")).unwrap(); // cycle let roots = vec![std::fs::canonicalize(&root).unwrap()]; let (mut budget, mut seen) = (super::STAGE_LIMIT, Default::default()); super::copy_tree(&root.join("skills"), &out, &roots, &mut budget, &mut seen).unwrap(); assert_eq!(std::fs::read_to_string(out.join("a/SKILL.md")).unwrap(), "ok"); assert!(!out.join("leak").exists()); std::fs::remove_dir_all(&t).unwrap(); } }