From 46ee1a817dbba065933d63810dc53def05f834eb Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Mon, 2 Nov 2026 08:49:01 -0800 Subject: [PATCH 01/27] mcp: port the automation roots onto the clap CLI The CLI's argument parsing moved to clap on main, so the hand-rolled parser and its McpTarget change are rebuilt as two options, a usage error naming to the modules main split out (wblock, import, export, plot, saveas, compare, template, the LISP file builtins). --- README.md | 2 + apps/cadcraft-cli/src/args.rs | 44 ++- apps/cadcraft-cli/src/error.rs | 3 + apps/cadcraft-cli/src/mcp.rs | 9 +- apps/cadcraft-cli/tests/mcp_roots.rs | 279 ++++++++++++++ crates/engine/src/cmd/audit.rs | 5 + crates/engine/src/cmd/blocks/extract.rs | 1 + crates/engine/src/cmd/blocks/insert_file.rs | 1 + crates/engine/src/cmd/blocks/wblock.rs | 2 + crates/engine/src/cmd/blocks/xref/load.rs | 1 + crates/engine/src/cmd/exchange.rs | 2 + crates/engine/src/cmd/file.rs | 4 + crates/engine/src/cmd/file/compare.rs | 6 +- crates/engine/src/cmd/file/template.rs | 2 + crates/engine/src/cmd/helpers.rs | 1 + crates/engine/src/cmd/layout.rs | 1 + crates/engine/src/cmd/layout/plotstyle.rs | 2 + crates/engine/src/cmd/layout/saveas.rs | 1 + crates/engine/src/cmd/plotters.rs | 1 + crates/engine/src/cmd/table/breaks.rs | 1 + crates/engine/src/cmd/table/cells.rs | 1 + crates/engine/src/file_access.rs | 387 ++++++++++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/lisp/builtins/files.rs | 8 +- crates/mcp/src/backend.rs | 32 +- docs/mcp.md | 38 ++ 26 files changed, 817 insertions(+), 18 deletions(-) create mode 100644 apps/cadcraft-cli/tests/mcp_roots.rs create mode 100644 crates/engine/src/file_access.rs diff --git a/README.md b/README.md index 611110c3cc..7d733348db 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,8 @@ The logger is `apps/cadcraft/src/logging.rs`; the web build logs to the browser cadcraft-cli mcp # …or bridged to the running app (start it with --control 7979): cadcraft-cli mcp --connect 127.0.0.1:7979 +# …or headless, with the agent confined to a work folder: +cadcraft-cli mcp --automation-read-root ~/work --automation-write-root ~/work/out # One-shot headless runs: cadcraft-cli run --sample --script 'CIRCLE 22,3 1\n' --save out.dxf --export out.png diff --git a/apps/cadcraft-cli/src/args.rs b/apps/cadcraft-cli/src/args.rs index f3b70fdc8b..9e7a0c3ed1 100644 --- a/apps/cadcraft-cli/src/args.rs +++ b/apps/cadcraft-cli/src/args.rs @@ -276,6 +276,12 @@ pub(crate) struct McpArgs { /// port first (macOS) #[arg(long, requires = "connect")] pub(crate) launch: bool, + /// The only folder the agent's commands may read from (headless only) + #[arg(long, value_name = "DIR")] + pub(crate) automation_read_root: Option, + /// The only folder the agent's commands may write to (headless only) + #[arg(long, value_name = "DIR")] + pub(crate) automation_write_root: Option, #[command(flatten)] pub(crate) settings: Settings, } @@ -408,12 +414,17 @@ enum UsageError { /// The output is one of the input files, so writing it would replace the original. #[error("{} is an input file, so the result would replace the original: choose another output, or pass --in-place to overwrite it", .0.display())] OutIsInput(PathBuf), + /// The automation roots confine the headless server; a running app enforces its own access. + #[error( + "--automation-read-root and --automation-write-root confine the headless MCP server; a running app enforces its own file access (not yet available: see issue #1585)" + )] + AutomationRootsNeedHeadless, } impl UsageError { fn into_clap(self, cmd: &mut clap::Command) -> clap::Error { let kind = match self { - Self::FramingNeedsImage { .. } | Self::OutIsInput(_) => ErrorKind::ArgumentConflict, + Self::FramingNeedsImage { .. } | Self::OutIsInput(_) | Self::AutomationRootsNeedHeadless => ErrorKind::ArgumentConflict, }; cmd.error(kind, self) } @@ -485,6 +496,13 @@ fn framing_error(cli: &Cli) -> Option { (!cadcraft_io::is_image(out)).then(|| UsageError::FramingNeedsImage { flag, out: out.to_path_buf() }) } +/// The automation roots confine the headless server only, as the other Craft apps' do. +fn roots_need_headless(cli: &Cli) -> Option { + let Command::Mcp(m) = &cli.command else { return None }; + (m.connect.is_some() && (m.automation_read_root.is_some() || m.automation_write_root.is_some())) + .then_some(UsageError::AutomationRootsNeedHeadless) +} + /// An output that is the same file as an input, without `--in-place`. An output that doesn't exist /// can't be an input, and an I/O error in the comparison is left to the open or write that follows. fn out_is_input(cli: &Cli) -> Option { @@ -503,8 +521,8 @@ fn out_is_input(cli: &Cli) -> Option { /// The backend `cadcraft-cli mcp` serves from. #[derive(Debug, PartialEq, Eq)] pub(crate) enum McpTarget { - /// An in-process drawing session (no `--connect`). - Headless, + /// An in-process drawing session (no `--connect`), optionally confined to the two folders. + Headless { read_root: Option, write_root: Option }, /// The running app's control channel at `HOST:PORT`; `lazy`: reached at the first call; /// `launch`: opened then if it isn't running. Connect { addr: String, lazy: bool, launch: bool }, @@ -515,7 +533,7 @@ impl McpArgs { match &self.connect { // `--launch` connects at the first call too (the app opens then). Some(addr) => McpTarget::Connect { addr: addr.clone(), lazy: self.lazy || self.launch, launch: self.launch }, - None => McpTarget::Headless, + None => McpTarget::Headless { read_root: self.automation_read_root.clone(), write_root: self.automation_write_root.clone() }, } } } @@ -588,7 +606,7 @@ fn parse_with(mut cmd: clap::Command, args: &[OsString]) -> Result = std::result::Result; diff --git a/apps/cadcraft-cli/src/mcp.rs b/apps/cadcraft-cli/src/mcp.rs index 960c80a5e1..4727d29c16 100644 --- a/apps/cadcraft-cli/src/mcp.rs +++ b/apps/cadcraft-cli/src/mcp.rs @@ -8,7 +8,14 @@ pub(crate) fn mcp(a: &McpArgs) -> Result { Ok(r) => Box::new(r), Err(source) => return Err(CliError::McpConnect { addr, source }), }, - McpTarget::Headless => Box::new(cadcraft_mcp::Headless::default()), + McpTarget::Headless { read_root, write_root } => { + let roots = cadcraft_engine::file_access::AutomationRoots::new( + read_root.as_deref().map(std::path::Path::new), + write_root.as_deref().map(std::path::Path::new), + ) + .map_err(CliError::AutomationRoots)?; + Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots)) + } }; let stdin = std::io::stdin(); let stdout = std::io::stdout(); diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs new file mode 100644 index 0000000000..67f205041d --- /dev/null +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -0,0 +1,279 @@ +//! `cadcraft-cli mcp --automation-read-root --automation-write-root ` (#1472): through +//! the MCP protocol, files open only from inside the read root and are saved, exported, plotted and +//! rendered only inside the write root; `..` and links that leave a root are refused, and nothing is +//! written outside. Without roots nothing changes. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Never crash). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; + +use serde_json::{Value, json}; + +const INIT: &str = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#; + +/// A folder holding `in` (the read root, with `a.dxf`), `out` (the write root), `outside` (with +/// `b.dxf`) and `in2` (a sibling with the same prefix as `in`). +fn folders(tag: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("cc-mcp-roots-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["in", "out", "outside", "in2"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + for p in ["in/a.dxf", "outside/b.dxf", "in2/c.dxf"] { + let drawing = cadcraft_engine::doc::Drawing::new_imperial(); + std::fs::write(base.join(p), cadcraft_io::write(&drawing, "x.dxf").unwrap()).unwrap(); + } + base +} + +fn s(p: &Path) -> String { + p.to_string_lossy().into_owned() +} + +/// One tool call's result: `isError` and its first text block. +struct Tool { + error: bool, + text: String, +} + +/// Run `cadcraft-cli mcp` with `args`, initialise, then make each call in order. +fn run(args: &[&str], calls: &[(&str, Value)]) -> (Output, Vec) { + let mut input = format!("{INIT}\n"); + for (i, (name, arguments)) in calls.iter().enumerate() { + let req = json!({"jsonrpc": "2.0", "id": i + 2, "method": "tools/call", "params": {"name": name, "arguments": arguments}}); + input.push_str(&req.to_string()); + input.push('\n'); + } + let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) + .arg("mcp") + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn cadcraft-cli"); + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(input.as_bytes()).unwrap(); + } + let out = child.wait_with_output().expect("wait for cadcraft-cli"); + let replies: Vec = String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| serde_json::from_str(l).ok()).collect(); + let tools = calls + .iter() + .enumerate() + .map(|(i, (name, arguments))| { + let id = (i + 2) as u64; + let reply = replies.iter().find(|v| v["id"] == id).unwrap_or_else(|| panic!("no reply to {name} {arguments}: {replies:?}")); + let result = &reply["result"]; + Tool { error: result["isError"] == true, text: result["content"][0]["text"].as_str().unwrap_or_default().to_string() } + }) + .collect(); + (out, tools) +} + +fn ok(t: &Tool) { + assert!(!t.error, "should be allowed: {}", t.text); +} + +fn refused(t: &Tool, why: &str) { + assert!(t.error, "should be refused ({why}): {}", t.text); + assert!(t.text.contains(why), "should say `{why}`: {}", t.text); +} + +#[test] +fn files_open_only_from_inside_the_read_root() { + let base = folders("open"); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[ + ("open", json!({"path": s(&base.join("in/a.dxf"))})), + ("open", json!({"path": s(&base.join("outside/b.dxf"))})), + ("open", json!({"path": s(&base.join("in2/c.dxf"))})), + ("open", json!({"path": format!("{}/../outside/b.dxf", s(&base.join("in")))})), + ("execute", json!({"command": "circle", "params": {"center": [0, 0], "radius": 1}})), + ], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + ok(&t[0]); + refused(&t[1], "outside the read root"); + refused(&t[2], "outside the read root"); + refused(&t[3], "outside the read root"); + // A refused path is an ordinary tool error; the session keeps working. + ok(&t[4]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn writes_go_only_into_the_write_root_and_leave_no_temp_file_outside() { + let base = folders("write"); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[ + ("open", json!({"path": s(&base.join("in/a.dxf"))})), + ("save", json!({"path": s(&base.join("out/saved.dxf"))})), + ("save", json!({"path": s(&base.join("outside/saved.dxf"))})), + ("save", json!({"path": s(&base.join("in/a.dxf"))})), + ("save", json!({"path": format!("{}/../outside/up.dxf", s(&base.join("out")))})), + ("execute", json!({"command": "export", "params": {"path": s(&base.join("out/art.png")), "format": "png"}})), + ("execute", json!({"command": "export", "params": {"path": s(&base.join("outside/art.png")), "format": "png"}})), + ("render", json!({"path": s(&base.join("out/view.png"))})), + ("render", json!({"path": s(&base.join("outside/view.png"))})), + ("execute", json!({"command": "circle", "params": {"center": [0, 0], "radius": 1}})), + ], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + ok(&t[0]); + ok(&t[1]); + assert!(base.join("out/saved.dxf").is_file()); + refused(&t[2], "outside the write root"); + refused(&t[3], "outside the write root"); + refused(&t[4], "outside the write root"); + ok(&t[5]); + assert!(base.join("out/art.png").is_file()); + refused(&t[6], "outside the write root"); + ok(&t[7]); + assert!(base.join("out/view.png").is_file()); + refused(&t[8], "outside the write root"); + ok(&t[9]); + + assert!(!base.join("outside/saved.dxf").exists()); + assert!(!base.join("outside/art.png").exists()); + assert!(!base.join("outside/view.png").exists()); + // The save's temporary file is beside the destination, inside the root; none is outside. + assert!(!base.join("outside/saved.dxf.cadcraft-tmp").exists()); + assert!(!base.join("outside/up.dxf.cadcraft-tmp").exists()); + let leftovers: Vec = + std::fs::read_dir(base.join("outside")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(leftovers, ["b.dxf"], "nothing was written outside the roots"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_root_left_out_grants_none_of_its_access() { + let base = folders("left-out"); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in"))], + &[("open", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": s(&base.join("out/a.dxf"))})), ("save", json!({}))], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + ok(&t[0]); + refused(&t[1], "write authority is absent"); + // QSAVE writes over the opened drawing's own path, which is not writable either. + refused(&t[2], "write authority is absent"); + + let (out, t) = run( + &["--automation-write-root", &s(&base.join("out"))], + &[("open", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": s(&base.join("out/new.dxf"))}))], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + refused(&t[0], "read authority is absent"); + ok(&t[1]); + assert!(base.join("out/new.dxf").is_file()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn without_roots_files_are_reachable_as_before() { + let base = folders("none"); + let (out, t) = + run(&[], &[("open", json!({"path": s(&base.join("outside/b.dxf"))})), ("save", json!({"path": s(&base.join("outside/new.dxf"))}))]); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + ok(&t[0]); + ok(&t[1]); + assert!(base.join("outside/new.dxf").is_file()); + let _ = std::fs::remove_dir_all(base); +} + +#[cfg(unix)] +#[test] +fn links_out_of_a_root_are_refused() { + let base = folders("links"); + std::os::unix::fs::symlink(base.join("outside"), base.join("out/away")).unwrap(); + std::os::unix::fs::symlink(base.join("outside/b.dxf"), base.join("in/leak.dxf")).unwrap(); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[("open", json!({"path": s(&base.join("in/leak.dxf"))})), ("save", json!({"path": s(&base.join("out/away/new.dxf"))}))], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + refused(&t[0], "outside the read root"); + refused(&t[1], "outside the write root"); + assert!(!base.join("outside/new.dxf").exists()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn every_file_a_command_touches_is_held_to_the_roots() { + let base = folders("commands"); + let drawing = cadcraft_engine::doc::Drawing::new_imperial(); + std::fs::write(base.join("in/x.dxf"), cadcraft_io::write(&drawing, "x.dxf").unwrap()).unwrap(); + std::fs::write(base.join("in/ok.scr"), "CIRCLE 0,0 1\n").unwrap(); + std::fs::write(base.join("outside/bad.scr"), "CIRCLE 0,0 1\n").unwrap(); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[ + ("open", json!({"path": s(&base.join("in/a.dxf"))})), + // SCRIPT + ("execute", json!({"command": "script", "params": {"path": s(&base.join("in/ok.scr"))}})), + ("execute", json!({"command": "script", "params": {"path": s(&base.join("outside/bad.scr"))}})), + // XATTACH reads the referenced drawing, INSERT and IMPORT read their files. + ("execute", json!({"command": "xattach", "params": {"path": s(&base.join("in/x.dxf")), "name": "ok"}})), + ("execute", json!({"command": "xattach", "params": {"path": s(&base.join("outside/b.dxf")), "name": "bad"}})), + ("execute", json!({"command": "insert", "params": {"name": "blk", "file": s(&base.join("outside/b.dxf")), "at": [0, 0]}})), + ("execute", json!({"command": "import", "params": {"path": s(&base.join("outside/b.dxf"))}})), + // Support files (a linetype file here) and a plot style table. + ("execute", json!({"command": "linetype", "params": {"file": s(&base.join("outside/b.dxf"))}})), + ("execute", json!({"command": "stylesmanager", "params": {"action": "load", "path": s(&base.join("outside/b.dxf"))}})), + // PLOT writes only inside the write root; the inside plot works. + ("execute", json!({"command": "plot", "params": {"path": s(&base.join("out/plot.pdf"))}})), + ("execute", json!({"command": "plot", "params": {"path": s(&base.join("outside/plot.pdf"))}})), + ], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + ok(&t[0]); + ok(&t[1]); + refused(&t[2], "outside the read root"); + ok(&t[3]); + refused(&t[4], "outside the read root"); + refused(&t[5], "outside the read root"); + refused(&t[6], "outside the read root"); + refused(&t[7], "outside the read root"); + refused(&t[8], "outside the read root"); + ok(&t[9]); + assert!(base.join("out/plot.pdf").is_file()); + refused(&t[10], "outside the write root"); + assert!(!base.join("outside/plot.pdf").exists()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn missing_roots_and_roots_with_connect_fail_at_startup() { + let base = folders("bad-roots"); + let input = format!("{INIT}\n"); + let start = |args: &[&str]| { + let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) + .arg("mcp") + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn cadcraft-cli"); + if let Some(mut stdin) = child.stdin.take() { + let _ = stdin.write_all(input.as_bytes()); + } + child.wait_with_output().expect("wait for cadcraft-cli") + }; + let out = start(&["--automation-read-root", &s(&base.join("nope"))]); + assert!(!out.status.success() && out.stdout.is_empty()); + assert!(String::from_utf8_lossy(&out.stderr).contains("cannot open the automation read root")); + + let out = start(&["--automation-write-root", &s(&base.join("in/a.dxf"))]); + assert!(!out.status.success() && out.stdout.is_empty()); + assert!(String::from_utf8_lossy(&out.stderr).contains("cannot open the automation write root")); + + let out = start(&["--connect", "127.0.0.1:1", "--automation-read-root", &s(&base.join("in"))]); + assert!(!out.status.success() && out.stdout.is_empty()); + assert!(String::from_utf8_lossy(&out.stderr).contains("headless MCP server")); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/cmd/audit.rs b/crates/engine/src/cmd/audit.rs index fa3cc2f988..d7b2813b83 100644 --- a/crates/engine/src/cmd/audit.rs +++ b/crates/engine/src/cmd/audit.rs @@ -143,6 +143,10 @@ fn write_audit_log(s: &Session, report: &crate::audit::Report) { // An unsaved drawing has no folder of its own to hold the log. let Some(path) = &path_str else { return }; let adt_path = std::path::PathBuf::from(path).with_extension("adt"); + if let Err(e) = crate::file_access::check_write(&adt_path.to_string_lossy()) { + log::warn!("AUDITCTL: not writing audit log {}: {e}", adt_path.display()); + return; + } let content = report.format_adt(&title, path_str.as_deref()); // Write through an exclusively-created temporary and rename over the companion path, so a // planted `.adt` symlink beside the drawing cannot redirect the report onto another file @@ -157,6 +161,7 @@ fn write_audit_log(_: &Session, _: &crate::audit::Report) {} #[cfg(not(target_arch = "wasm32"))] fn read_path(cmd: &str, path: &str) -> Result> { + crate::file_access::check_read(path).map_err(|e| bad(cmd, e))?; std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}"))) } diff --git a/crates/engine/src/cmd/blocks/extract.rs b/crates/engine/src/cmd/blocks/extract.rs index 10785f08f1..ecb2ca5408 100644 --- a/crates/engine/src/cmd/blocks/extract.rs +++ b/crates/engine/src/cmd/blocks/extract.rs @@ -203,6 +203,7 @@ fn csv(columns: &[String], rows: &[Vec], sep: char) -> String { fn write_file(path: &str, text: &str) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_write(path).map_err(EngineError::Other)?; std::fs::write(path, text).map_err(|e| EngineError::Other(format!("{path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index 7a0492fad8..650bf94689 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -85,6 +85,7 @@ fn read_drawing(path: &str) -> Result { fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(_path).map_err(|e| bad("insert", e))?; std::fs::read(_path).map_err(|e| bad("insert", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs index 373e471bfe..79b9955b26 100644 --- a/crates/engine/src/cmd/blocks/wblock.rs +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -105,6 +105,8 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi let bytes = (hooks.write)(&d, path).map_err(|e| bad(cmd, e))?; // Through a temporary file, as SAVE writes, so a failed write keeps the file it replaces. #[cfg(not(target_arch = "wasm32"))] + crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?; + #[cfg(not(target_arch = "wasm32"))] crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; let lost = if drops_unknown(path) { not_saved(&d) } else { BTreeMap::new() }; Ok((d.model.len(), bytes.len(), lost)) diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index 981df918dc..6522e8e180 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -261,6 +261,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { #[cfg(not(target_arch = "wasm32"))] { use std::io::Read; + crate::file_access::check_read(&file.to_string_lossy())?; let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes); let limit = MAX_XREF_BYTES.min(left); let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?; diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index b90fa5e671..9f586978cd 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -82,6 +82,7 @@ fn write_file(cmd: &str, path: &str, bytes: &[u8]) -> Result<()> { { // Exclusively create a fresh temporary file and rename it into place so a planted // `.cadcraft-tmp` symlink cannot redirect the export write (CWE-59). + crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?; crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), bytes).map_err(|e| bad(cmd, format!("{path}: {e}"))) } #[cfg(target_arch = "wasm32")] @@ -204,6 +205,7 @@ fn import_drawing(s: &mut Session, src: &Drawing, at: Vec2, scale: f64, file: &s fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(_path).map_err(|e| bad("import", e))?; std::fs::read(_path).map_err(|e| bad("import", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 606ad4e288..2b298e8895 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -224,6 +224,7 @@ fn run_script(s: &mut Session, p: &Value) -> Result { let path = _path; #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(path).map_err(|e| bad("script", e))?; let bytes = crate::capped_read::read_capped(std::path::Path::new(path), MAX_SCRIPT_BYTES).map_err(|e| bad("script", format!("{path}: {e}")))?; String::from_utf8_lossy(&bytes).into_owned() @@ -304,6 +305,7 @@ pub fn read_file(path: &std::path::Path) -> std::result::Result Result { let path = _path; #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(path).map_err(|e| bad("open", e))?; let bytes = crate::capped_read::read_capped(std::path::Path::new(path), MAX_DRAWING_BYTES).map_err(|e| bad("open", format!("{path}: {e}")))?; let i = open_bytes(s, &bytes, path, Some(path.to_string()))?; @@ -462,6 +465,7 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result Result<()> { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_write(path).map_err(|e| bad("save", e))?; // A file in a folder still to be made has nothing to back up. if is_drawing_file(path) && crate::autosave::isavebak() && crate::atomic_write::missing_folder(std::path::Path::new(path)).is_none() { backup(std::path::Path::new(path)) diff --git a/crates/engine/src/cmd/file/compare.rs b/crates/engine/src/cmd/file/compare.rs index 295b472b1c..3af713cd44 100644 --- a/crates/engine/src/cmd/file/compare.rs +++ b/crates/engine/src/cmd/file/compare.rs @@ -110,7 +110,11 @@ fn other_drawing(s: &Session, p: &Value) -> Result<(Arc, String)> { fn read_path(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { - std::fs::read(_path).map_err(|e| bad("compare", format!("{_path}: {e}"))) + crate::file_access::check_read(_path).map_err(|e| bad("compare", e))?; + { + crate::file_access::check_read(_path).map_err(|e| bad("compare", e))?; + std::fs::read(_path).map_err(|e| bad("compare", format!("{_path}: {e}"))) + } } #[cfg(target_arch = "wasm32")] Err(bad("compare", "paths are not available on the web: open the other drawing and compare with it by name (`document`)")) diff --git a/crates/engine/src/cmd/file/template.rs b/crates/engine/src/cmd/file/template.rs index 11d6f29266..7608eb1243 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -74,6 +74,8 @@ fn read_template(path: &str) -> Result { #[cfg(not(target_arch = "wasm32"))] fn read_bytes(path: &str) -> Result> { + crate::file_access::check_read(path).map_err(|e| bad("new", e))?; + crate::file_access::check_read(path).map_err(|e| bad("new", e))?; std::fs::read(path).map_err(|e| bad("new", format!("template {path}: {e}"))) } diff --git a/crates/engine/src/cmd/helpers.rs b/crates/engine/src/cmd/helpers.rs index ed5891203d..b689900488 100644 --- a/crates/engine/src/cmd/helpers.rs +++ b/crates/engine/src/cmd/helpers.rs @@ -117,6 +117,7 @@ pub fn support_text(cmd: &str, p: &serde_json::Value, path_key: &str, text_key: #[cfg(not(target_arch = "wasm32"))] fn read_support_file(cmd: &str, path: &str) -> crate::Result { use std::io::Read; + crate::file_access::check_read(path).map_err(|e| super::bad(cmd, e))?; let f = std::fs::File::open(path).map_err(|e| super::bad(cmd, format!("{path}: {e}")))?; let mut bytes = Vec::new(); f.take(MAX_SUPPORT_FILE_BYTES + 1).read_to_end(&mut bytes).map_err(|e| super::bad(cmd, format!("{path}: {e}")))?; diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index f6b519a3c0..8abddba520 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -841,6 +841,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { let path = _path; // Exclusively create a fresh temporary file and rename it into place so a planted // `.cadcraft-tmp` symlink cannot redirect the plot write (CWE-59). + crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?; let folder = super::file::new_folder(path); crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages }); diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index d432343c2c..ef6c2edabf 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -303,6 +303,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { (None, Some(_path)) => { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(_path).map_err(|e| bad(cmd, e))?; let meta = std::fs::metadata(_path).map_err(|e| bad(cmd, format!("{_path}: {e}")))?; if meta.len() > cadcraft_doc::MAX_TABLE_FILE as u64 { return Err(bad(cmd, format!("{_path}: the plot style table file is too large"))); @@ -333,6 +334,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { Some(_path) => { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_write(_path).map_err(|e| bad(cmd, e))?; crate::atomic_write::write_atomic(std::path::Path::new(_path), text.as_bytes()) .map_err(|e| bad(cmd, format!("{_path}: {e}")))?; Ok(json!({ "name": name, "path": _path, "bytes": text.len() })) diff --git a/crates/engine/src/cmd/layout/saveas.rs b/crates/engine/src/cmd/layout/saveas.rs index 0a0b2b5f8e..f697285c5f 100644 --- a/crates/engine/src/cmd/layout/saveas.rs +++ b/crates/engine/src/cmd/layout/saveas.rs @@ -126,6 +126,7 @@ fn store(path: &str, bytes: &[u8]) -> Result<()> { { // Exclusively create a fresh temporary file and rename it into place so a planted // `.cadcraft-tmp` symlink cannot redirect the write (CWE-59). + crate::file_access::check_write(path).map_err(|e| bad("layout.saveas", e))?; crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), bytes).map_err(|e| bad("layout.saveas", format!("{path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 95ead78fcc..d5f7382338 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -598,6 +598,7 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result { Some(_path) => { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_write(_path).map_err(|e| bad(cmd, e))?; std::fs::write(_path, &text).map_err(|e| bad(cmd, format!("{_path}: {e}")))?; Ok(json!({ "name": name, "path": _path })) } diff --git a/crates/engine/src/cmd/table/breaks.rs b/crates/engine/src/cmd/table/breaks.rs index 6f207ec500..63504de55d 100644 --- a/crates/engine/src/cmd/table/breaks.rs +++ b/crates/engine/src/cmd/table/breaks.rs @@ -238,6 +238,7 @@ fn read_link(id: &str, file: &std::path::Path) -> Result { let path = file.display(); #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(&file.to_string_lossy()).map_err(|e| bad(id, e))?; let meta = std::fs::metadata(file).map_err(|e| bad(id, format!("{path}: {e}")))?; if meta.len() > MAX_LINK_BYTES { return Err(bad(id, format!("{path}: larger than {} MB", MAX_LINK_BYTES >> 20))); diff --git a/crates/engine/src/cmd/table/cells.rs b/crates/engine/src/cmd/table/cells.rs index d020758d8b..f7c6950366 100644 --- a/crates/engine/src/cmd/table/cells.rs +++ b/crates/engine/src/cmd/table/cells.rs @@ -514,6 +514,7 @@ pub(crate) fn table_csv(t: &Table, sep: char) -> String { fn write_text(path: &str, text: &str) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_write(path).map_err(|e| bad("tableexport", e))?; std::fs::write(path, text).map_err(|e| bad("tableexport", format!("{path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs new file mode 100644 index 0000000000..78e237ad4a --- /dev/null +++ b/crates/engine/src/file_access.rs @@ -0,0 +1,387 @@ +//! The folders automation may read and write (#1472). +//! +//! `cadcraft-cli mcp --automation-read-root --automation-write-root ` confines the files +//! an agent's commands reach. [`AutomationRoots`] holds the two folders. While they are in force, +//! every path a command reads goes through [`check_read`] and every path it writes through +//! [`check_write`]: +//! +//! - The path is made absolute against the working directory, as the file system reads it. Its +//! links are followed: for a file that doesn't exist yet, the links of its nearest existing +//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so +//! is a link that leads nowhere). +//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside +//! `/work`), without regard to case on Windows. +//! - Read and write access are separate: a root given alone grants only its own kind of access. +//! A root left out grants none of that access. +//! +//! Roots are in force on a thread inside [`confine`]. The MCP headless backend runs every call in +//! it; without roots nothing is checked, so the app and the command line keep working everywhere. +//! +//! A path is checked, then opened: a process that can change the folders in between (swapping in +//! a link) can still win that race. The roots keep an agent to the files it was given; they don't +//! guard against other programs on the computer. + +use std::cell::RefCell; +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; + +/// Read access or write access. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Access { + Read, + Write, +} + +/// The folders automation may read and write; a root left out grants no access of its kind. +#[derive(Debug)] +pub struct AutomationRoots { + read: Option, + write: Option, +} + +#[derive(Debug)] +struct Root { + /// The folder made absolute, links followed: what paths are compared with. + resolved: PathBuf, + /// The same path, for people. + shown: PathBuf, +} + +impl Root { + /// The folder at `path`, which must exist. + fn open(path: &Path, access: Access) -> Result { + let kind = match access { + Access::Read => "read", + Access::Write => "write", + }; + let resolved = std::fs::canonicalize(path) + .and_then(|p| if p.is_dir() { Ok(p) } else { Err(std::io::ErrorKind::NotADirectory.into()) }) + .map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display()))?; + Ok(Self { shown: resolved.clone(), resolved }) + } +} + +impl AutomationRoots { + /// The roots `read` and `write`, which must be existing folders; `None` when neither is given + /// (nothing is confined then). + pub fn new(read: Option<&Path>, write: Option<&Path>) -> Result>, String> { + if read.is_none() && write.is_none() { + return Ok(None); + } + let read = read.map(|p| Root::open(p, Access::Read)).transpose()?; + let write = write.map(|p| Root::open(p, Access::Write)).transpose()?; + Ok(Some(Arc::new(Self { read, write }))) + } + + /// The read root, absolute with its links followed. + pub fn read_root(&self) -> Option<&Path> { + self.read.as_ref().map(|r| r.shown.as_path()) + } + + /// The write root, absolute with its links followed. + pub fn write_root(&self) -> Option<&Path> { + self.write.as_ref().map(|r| r.shown.as_path()) + } + + /// May the file or folder at `path` be read (or written)? `Err` says why not. + pub fn check(&self, path: &str, access: Access) -> Result<(), String> { + let root = match access { + Access::Read => self.read.as_ref(), + Access::Write => self.write.as_ref(), + }; + let Some(Root { resolved: folder, shown }) = root else { + return match access { + Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")), + Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")), + }; + }; + if inside(&resolve(path)?, folder) { + return Ok(()); + } + let root = shown.display(); + match access { + Access::Read => Err(format!("automation path rejected: outside the read root {root}: {path}")), + Access::Write => Err(format!("automation path rejected: outside the write root {root}: {path}")), + } + } +} + +thread_local! { + /// The roots in force on this thread. + static ROOTS: RefCell>> = const { RefCell::new(None) }; +} + +/// Puts the roots it replaced back when dropped (also when `f` panics). +struct Restore(Option>); + +impl Drop for Restore { + fn drop(&mut self) { + ROOTS.with(|r| *r.borrow_mut() = self.0.take()); + } +} + +/// Run `f` with `roots` in force on this thread (`None`: as things stand). +pub fn confine(roots: Option<&Arc>, f: impl FnOnce() -> T) -> T { + let previous = ROOTS.with(|r| r.replace(roots.cloned())); + let _restore = Restore(previous); + f() +} + +/// This thread's roots, if any. +pub fn current() -> Option> { + ROOTS.with(|r| r.borrow().clone()) +} + +/// May `path` be read here? Always, without roots in force. +pub fn check_read(path: &str) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check(path, Access::Read)) +} + +/// May `path` be written here? Always, without roots in force. +pub fn check_write(path: &str) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check(path, Access::Write)) +} + +/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest +/// existing folder's links followed and the rest appended. +fn resolve(path: &str) -> Result { + if path.is_empty() { + return Err("automation path rejected: path is empty".into()); + } + // Checked as given: making `…\NUL` absolute gives the device path `\\.\NUL` on Windows. + if cfg!(windows) && Path::new(path).components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) { + return Err(format!("automation path rejected: reserved device names are not allowed: {path}")); + } + let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {path}: {e}"))?; + // The names below the nearest existing folder, last first. + let mut missing: Vec = vec![]; + let mut at = absolute.as_path(); + loop { + match std::fs::canonicalize(at) { + Ok(mut found) => { + found.extend(missing.iter().rev()); + return Ok(found); + } + Err(e) => match std::fs::symlink_metadata(at) { + Ok(m) if m.file_type().is_symlink() => return Err(format!("automation path rejected: a link that leads nowhere: {path}")), + // There, yet its real path can't be had (no permission): nothing to compare. + Ok(_) => return Err(format!("automation path rejected: cannot resolve {path}: {e}")), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("automation path rejected: cannot resolve {path}: {e}")), + }, + } + let parent = at.parent(); + match (at.components().next_back(), parent) { + (Some(Component::Normal(name)), Some(parent)) => { + missing.push(name.to_os_string()); + at = parent; + } + (Some(Component::ParentDir), _) => { + return Err(format!("automation path rejected: parent traversal below a folder that doesn't exist: {path}")); + } + // Down to the root (or drive) and it doesn't exist either. + _ => { + let e = std::io::Error::from(std::io::ErrorKind::NotFound); + return Err(format!("automation path rejected: cannot resolve {path}: {e}")); + } + } + } +} + +/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on +/// Windows, whose file systems ignore it)? +fn inside(path: &Path, root: &Path) -> bool { + let mut path = path.components(); + root.components().all(|r| path.next().is_some_and(|p| same_component(p, r))) +} + +fn same_component(a: Component, b: Component) -> bool { + if a == b { + return true; + } + if !cfg!(windows) { + return false; + } + match (a.as_os_str().to_str(), b.as_os_str().to_str()) { + (Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(), + _ => false, + } +} + +/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file. +fn is_device_name(component: &str) -> bool { + let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); + let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")); + matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A fresh folder holding `in` (read root), `out` (write root) and `outside`. + fn folders(name: &str) -> (PathBuf, Arc) { + let base = std::env::temp_dir().join(format!("cc-file-access-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["in/sub", "out", "outside", "in2"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + std::fs::write(base.join("in/a.dxf"), "0\nEOF\n").unwrap(); + std::fs::write(base.join("outside/secret.dxf"), "0\nEOF\n").unwrap(); + let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("out"))).unwrap().unwrap(); + (base, roots) + } + + fn s(p: PathBuf) -> String { + p.to_string_lossy().into_owned() + } + + #[test] + fn paths_inside_the_roots_pass_and_others_dont() { + let (base, roots) = folders("inside"); + assert_eq!(roots.check(&s(base.join("in/a.dxf")), Access::Read), Ok(())); + assert_eq!(roots.check(&s(base.join("in")), Access::Read), Ok(()), "the root itself"); + assert_eq!(roots.check(&s(base.join("in/sub/new.dxf")), Access::Read), Ok(()), "missing files are checked by their folder"); + assert_eq!(roots.check(&s(base.join("out/new/deeper/x.png")), Access::Write), Ok(()), "and by their nearest folder"); + let e = roots.check(&s(base.join("outside/secret.dxf")), Access::Read).unwrap_err(); + assert!(e.starts_with("automation path rejected: outside the read root"), "{e}"); + // Read and write access are separate. + let e = roots.check(&s(base.join("in/a.dxf")), Access::Write).unwrap_err(); + assert!(e.contains("outside the write root"), "{e}"); + assert!(roots.check(&s(base.join("out/x.png")), Access::Read).unwrap_err().contains("outside the read root")); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn a_sibling_with_the_same_prefix_is_outside() { + let (base, roots) = folders("prefix"); + std::fs::write(base.join("in2/b.dxf"), "0\nEOF\n").unwrap(); + assert!(roots.check(&s(base.join("in2/b.dxf")), Access::Read).is_err(), "in2 is not inside in"); + assert!(roots.check(&format!("{}2/c.dxf", s(base.join("in"))), Access::Read).is_err()); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn parent_traversal_is_resolved_or_refused() { + let (base, roots) = folders("dotdot"); + let sep = std::path::MAIN_SEPARATOR; + let up = format!("{}{sep}..{sep}outside{sep}secret.dxf", s(base.join("in"))); + assert!(roots.check(&up, Access::Read).unwrap_err().contains("outside the read root"), "`..` out of the root"); + let back = format!("{}{sep}..{sep}a.dxf", s(base.join("in/sub"))); + assert_eq!(roots.check(&back, Access::Read), Ok(()), "`..` that stays inside"); + let missing = format!("{}{sep}nope{sep}..{sep}..{sep}outside{sep}x.dxf", s(base.join("out"))); + let e = roots.check(&missing, Access::Write).unwrap_err(); + // Windows resolves `..` by name first (so does opening the file there): then it's outside. + assert!(e.contains("parent traversal below a folder that doesn't exist") || e.contains("outside the write root"), "{e}"); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn relative_paths_resolve_against_the_working_directory() { + let (base, roots) = folders("relative"); + // The tests' working directory is the crate's folder: not inside the roots. + assert!(roots.check("a.dxf", Access::Read).unwrap_err().contains("outside the read root")); + assert!(roots.check("", Access::Read).unwrap_err().contains("path is empty")); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn a_missing_root_is_an_error_and_none_is_no_confinement() { + let (base, _) = folders("missing"); + let e = AutomationRoots::new(Some(&base.join("nope")), None).unwrap_err(); + assert!(e.starts_with("cannot open the automation read root"), "{e}"); + let e = AutomationRoots::new(None, Some(&base.join("in/a.dxf"))).unwrap_err(); + assert!( + e.starts_with("cannot open the automation write root") + && e.ends_with(&std::io::Error::from(std::io::ErrorKind::NotADirectory).to_string()), + "{e}" + ); + assert!(AutomationRoots::new(Some(Path::new("")), None).unwrap_err().starts_with("cannot open the automation read root ``")); + assert!(AutomationRoots::new(None, None).unwrap().is_none()); + // One root alone grants only its own access. + let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); + let e = read_only.check(&s(base.join("in/x.dxf")), Access::Write).unwrap_err(); + assert!(e.contains("write authority is absent"), "{e}"); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn links_are_followed_before_comparing() { + let (base, roots) = folders("links"); + #[cfg(unix)] + let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); + #[cfg(windows)] + let made = |target: &Path, link: &Path| { + let made = + if target.is_dir() { std::os::windows::fs::symlink_dir(target, link) } else { std::os::windows::fs::symlink_file(target, link) }; + made.is_ok() + }; + #[cfg(not(any(unix, windows)))] + let made = |_: &Path, _: &Path| false; + // Windows needs Developer Mode or elevation to make links: nothing to test without them. + if !made(&base.join("outside/secret.dxf"), &base.join("in/leak.dxf")) { + eprintln!("skipped: symbolic links can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + assert!(roots.check(&s(base.join("in/leak.dxf")), Access::Read).unwrap_err().contains("outside the read root"), "a file link out"); + assert!(made(&base.join("outside"), &base.join("out/away"))); + let e = roots.check(&s(base.join("out/away/new.png")), Access::Write).unwrap_err(); + assert!(e.contains("outside the write root"), "a folder link out: {e}"); + assert!(made(&base.join("outside/gone.dxf"), &base.join("out/dangling.png"))); + let e = roots.check(&s(base.join("out/dangling.png")), Access::Write).unwrap_err(); + assert!(e.contains("a link that leads nowhere"), "writing would create the file outside: {e}"); + // A link to a folder inside the root stays inside. + assert!(made(&base.join("in/sub"), &base.join("in/alias"))); + assert_eq!(roots.check(&s(base.join("in/alias/x.dxf")), Access::Read), Ok(())); + // A root given through a link is the folder it leads to. + assert!(made(&base.join("in"), &base.join("in-link"))); + let linked = AutomationRoots::new(Some(&base.join("in-link")), None).unwrap().unwrap(); + assert_eq!(linked.check(&s(base.join("in/a.dxf")), Access::Read), Ok(())); + let _ = std::fs::remove_dir_all(base); + } + + #[cfg(windows)] + #[test] + fn windows_ignores_case_and_refuses_devices() { + let (base, roots) = folders("case"); + let upper = s(base.join("IN/A.DXF")); + assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}"); + assert_eq!(roots.check(&s(base.join("In/Sub/New.dxf")), Access::Read), Ok(())); + let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err(); + assert!(e.contains("reserved device names"), "{e}"); + assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err()); + assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(())); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn scopes_nest_and_restore_after_a_panic() { + let (base, roots) = folders("scopes"); + let outside = s(base.join("outside/secret.dxf")); + assert_eq!(check_read(&outside), Ok(()), "nothing is confined by default"); + confine(Some(&roots), || { + assert!(check_read(&outside).is_err()); + // A nested scope replaces the outer one and gives it back on the way out. + confine(None, || assert_eq!(check_read(&outside), Ok(()))); + assert!(check_read(&outside).is_err(), "restored after the inner scope"); + }); + assert_eq!(check_read(&outside), Ok(()), "restored after confine"); + let r = std::panic::catch_unwind(|| confine(Some(&roots), || panic!("boom"))); + assert!(r.is_err()); + assert_eq!(check_read(&outside), Ok(()), "restored after a panic"); + assert_eq!(confine(None, || check_read(&outside)), Ok(())); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn device_names() { + for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL "] { + assert!(is_device_name(d), "{d}"); + } + for f in ["console", "com10", "COM0", "lpt", "a.svg", "nul-x"] { + assert!(!is_device_name(f), "{f}"); + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ccb93ef4f7..809e1fa8a5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -18,6 +18,7 @@ pub mod blockedit; pub mod capped_read; pub mod cmd; pub mod doc_path; +pub mod file_access; mod finite; pub mod grip_dims; pub mod grips; diff --git a/crates/engine/src/lisp/builtins/files.rs b/crates/engine/src/lisp/builtins/files.rs index 44452ae892..00c8788fab 100644 --- a/crates/engine/src/lisp/builtins/files.rs +++ b/crates/engine/src/lisp/builtins/files.rs @@ -32,7 +32,7 @@ pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec) -> Result } None => return Ok(Flow::Value(Value::Nil)), } - } else if !can_write(&path) { + } else if !can_write(&path) || crate::file_access::check_write(&path).is_err() { return Ok(Flow::Value(Value::Nil)); } let id = ctx.env.next_file; @@ -77,6 +77,7 @@ pub fn read_text_file(path: impl AsRef) -> Option { // Read through a byte-limited, regular-file-only reader so a path naming an endless device // cannot exhaust memory before the 64 MiB cap is enforced (CWE-400). const MAX: usize = 64 * 1024 * 1024; + crate::file_access::check_read(&path.as_ref().to_string_lossy()).ok()?; let bytes = crate::capped_read::read_capped(path.as_ref(), MAX).ok()?; Some(String::from_utf8_lossy(&bytes).into_owned()) } @@ -100,6 +101,9 @@ fn can_write(_path: &str) -> bool { #[cfg(not(target_arch = "wasm32"))] fn write_text_file(path: &str, text: &str, append: bool) { use std::io::Write; + if crate::file_access::check_write(path).is_err() { + return; + } let f = std::fs::OpenOptions::new().create(true).write(true).append(append).truncate(!append).open(path); if let Ok(mut f) = f { let _ = f.write_all(text.as_bytes()); @@ -111,7 +115,7 @@ fn write_text_file(_path: &str, _text: &str, _append: bool) {} #[cfg(not(target_arch = "wasm32"))] fn file_exists(path: &str) -> bool { - std::path::Path::new(path).is_file() + crate::file_access::check_read(path).is_ok() && std::path::Path::new(path).is_file() } #[cfg(target_arch = "wasm32")] diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 913569e824..af2e9bc9ea 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -2,9 +2,11 @@ use std::io::{BufRead, BufReader, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; +use std::sync::Arc; use std::time::Duration; use cadcraft_engine::Session; +use cadcraft_engine::file_access::{self, AutomationRoots}; use serde_json::{Value, json}; /// Something that answers control-channel methods (`engine.execute`, `cmdline.input`, @@ -308,13 +310,19 @@ const HEADLESS_METHODS: &[(&str, &str, &str)] = &[ ]; /// An in-process headless session (no window). +#[derive(Default)] pub struct Headless { pub session: Session, + /// The folders its methods may read and write (`--automation-read-root`, + /// `--automation-write-root`); `None`: anywhere. + roots: Option>, } -impl Default for Headless { - fn default() -> Self { - Headless { session: Session::new() } +impl Headless { + /// Confine the files every method reads and writes to `roots` ([`file_access`]). + pub fn with_automation_roots(mut self, roots: Option>) -> Self { + self.roots = roots; + self } } @@ -333,8 +341,8 @@ fn state(s: &Session) -> Value { }) } -impl Backend for Headless { - fn call(&mut self, method: &str, p: Value) -> Result { +impl Headless { + fn answer(&mut self, method: &str, p: &Value) -> Result { let s = &mut self.session; let str_p = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); match method { @@ -394,12 +402,12 @@ impl Backend for Headless { "engine.commands" => { Ok(Value::Array(cadcraft_engine::command_specs().iter().map(|c| serde_json::to_value(c.info(s)).unwrap_or_default()).collect())) } - "drawing.inspect" | "document.inspect" => s.execute("drawing.inspect", &p).map_err(|e| e.to_string()), + "drawing.inspect" | "document.inspect" => s.execute("drawing.inspect", p).map_err(|e| e.to_string()), "ui.render" => { let w = p.get("width").and_then(Value::as_f64).unwrap_or(1600.0).clamp(16.0, 8192.0) as u32; let h = p.get("height").and_then(Value::as_f64).unwrap_or(1000.0).clamp(16.0, 8192.0) as u32; let st = s.state().map_err(|e| e.to_string())?; - let window = render_window(&p); + let window = render_window(p); let opts = cadcraft_render::Options { view: window, transparency: s.settings.transparency_display, ..Default::default() }; let list = cadcraft_render::build(&st.doc, &st.space, &opts); let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(true); @@ -418,6 +426,7 @@ impl Backend for Headless { let mut r = json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "truncated": list.truncated}); if let Some(path) = str_p("path") { + file_access::check_write(&path)?; let file = std::path::Path::new(&path); let folder = cadcraft_engine::atomic_write::missing_folder(file); cadcraft_engine::atomic_write::write_atomic_making_folders(file, &png).map_err(|e| format!("{path}: {e}"))?; @@ -433,7 +442,7 @@ impl Backend for Headless { } "app.save" => { let id = if p.get("path").is_some() { "saveas" } else { "qsave" }; - s.execute(id, &p).map_err(|e| e.to_string()) + s.execute(id, p).map_err(|e| e.to_string()) } "ui.screenshot" => Err("no UI in headless mode; use render".into()), "control.methods" => Ok(HEADLESS_METHODS @@ -444,6 +453,13 @@ impl Backend for Headless { other => Err(format!("unknown method `{other}`; `control.methods` lists them (docs/control-protocol.md)")), } } +} + +impl Backend for Headless { + fn call(&mut self, method: &str, p: Value) -> Result { + let roots = self.roots.clone(); + file_access::confine(roots.as_ref(), || self.answer(method, &p)) + } fn has_ui(&self) -> bool { false } diff --git a/docs/mcp.md b/docs/mcp.md index ecdc53d095..fa76d3452c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -32,6 +32,44 @@ Example client configuration (Claude Code / Claude Desktop): { "mcpServers": { "cadcraft": { "command": "cadcraft-cli", "args": ["mcp"] } } } ``` +## Confining file access + +```sh +cadcraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project/out +``` + +The two flags (PhotoCraft, VectorCraft and the other Craft apps take the same ones, so one client +configuration works across the suite) keep the agent to the folders you give it: + +- Every file a command **reads** must lie inside the **read root**: `open`, `recover`, `compare`, + `script`, `import`, `insert`, `xattach` and every xref it loads, `new` templates, `appload` and + LISP `load`/`open`, support files (`linetype`, `hatch.patterns`, `aliasedit`, `reinit`), data + links, and plot style and plotter configuration files named by a path. +- Every file a command **writes** must lie inside the **write root**: `save`/`qsave`/`saveas` + (including the temporary file written beside the destination), `export`, `plot`, `publish`, + `pdfbook`, `wblock`, data extraction, table export, plot style and plotter saves, and + `render {path}`. +- Read and write access are separate. Give the same folder twice for both; a root left out grants + none of its access (with only `--automation-read-root`, nothing can be written to disk). Without + either flag nothing changes. +- A path is made absolute against the server's working directory, then its links are followed: a + file or folder link that leads out of a root is outside it. For a file that doesn't exist yet, + its nearest existing folder's links are followed and the rest must be plain names, so `..` below + a folder that doesn't exist is refused, as is a link that leads nowhere. The result is compared + with the root by whole folder names: `/work2/x` is not inside `/work`. On Windows case is ignored, + UNC paths are resolved like drive-letter ones, and device names (`CON`, `NUL`, `COM1`…) are + refused. +- A refused path is an ordinary tool error with `isError: true` that the agent can read and + correct, for example `automation path rejected: outside the write root + /work/project/out: /etc/x.png` or `automation filesystem access is not granted: write authority + is absent: /work/project/out/x.png`. +- The roots must be existing folders; a missing one stops the server with an error. Each flag is + given once (`--flag ` or `--flag=`). + +The flags confine the headless server. `--connect` with them is an error, since the server would +otherwise talk to an app that isn't confined; the app's control channel does not take them yet +(#1585). Without `--connect` the server writes the files itself, so every check happens here. + ## Tools | Tool | What it does | From 0f33f430a75a28145b24f540e4f5b553f7070012 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 05:50:44 -0700 Subject: [PATCH 02/27] security: confine plotter settings I/O and refuse the write root itself - PLOTTERMANAGER's settings store now checks read access to the settings folder and each file, write access to the target before the folder is created, and write access before deletion (#1472 review). list surfaces a refused folder as an ordinary error. - Reads are allowed under the read or the write root; writes stay under the write root. A write to the write root itself is refused, since its temporary file would land beside the root, outside it. - Tests cover reads under either root, refusing the root as a write target, no temporary file outside the root, and every plotter action refused when the shared settings folder is outside the roots. - Docs and CLI help describe the same rules. This is 72961da from the #1904 branch, which the 2 Nov rebase dropped, ported to main's atomic_write. Main's writers now use a fresh temporary file beside the target, so the separate temporary-path checks are gone. --- apps/cadcraft-cli/src/args.rs | 5 +- apps/cadcraft-cli/tests/mcp_roots.rs | 86 +++++++++++++++++++++++++--- crates/engine/src/cmd/plotters.rs | 35 ++++++++++- crates/engine/src/file_access.rs | 83 +++++++++++++++++++++------ docs/mcp.md | 26 +++++---- 5 files changed, 191 insertions(+), 44 deletions(-) diff --git a/apps/cadcraft-cli/src/args.rs b/apps/cadcraft-cli/src/args.rs index 9e7a0c3ed1..5d3864e0e7 100644 --- a/apps/cadcraft-cli/src/args.rs +++ b/apps/cadcraft-cli/src/args.rs @@ -276,10 +276,11 @@ pub(crate) struct McpArgs { /// port first (macOS) #[arg(long, requires = "connect")] pub(crate) launch: bool, - /// The only folder the agent's commands may read from (headless only) + /// The only folder the agent's commands may read from; reads are also allowed under the write + /// root (headless only) #[arg(long, value_name = "DIR")] pub(crate) automation_read_root: Option, - /// The only folder the agent's commands may write to (headless only) + /// The only folder the agent's commands may write to, never the folder itself (headless only) #[arg(long, value_name = "DIR")] pub(crate) automation_write_root: Option, #[command(flatten)] diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs index 67f205041d..71e38adc04 100644 --- a/apps/cadcraft-cli/tests/mcp_roots.rs +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -40,6 +40,11 @@ struct Tool { /// Run `cadcraft-cli mcp` with `args`, initialise, then make each call in order. fn run(args: &[&str], calls: &[(&str, Value)]) -> (Output, Vec) { + run_env(args, calls, &[]) +} + +/// [`run`], with `env` set for the server process (a private settings folder). +fn run_env(args: &[&str], calls: &[(&str, Value)], env: &[(&str, &str)]) -> (Output, Vec) { let mut input = format!("{INIT}\n"); for (i, (name, arguments)) in calls.iter().enumerate() { let req = json!({"jsonrpc": "2.0", "id": i + 2, "method": "tools/call", "params": {"name": name, "arguments": arguments}}); @@ -49,6 +54,7 @@ fn run(args: &[&str], calls: &[(&str, Value)]) -> (Output, Vec) { let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) .arg("mcp") .args(args) + .envs(env.iter().copied()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -104,17 +110,21 @@ fn files_open_only_from_inside_the_read_root() { let _ = std::fs::remove_dir_all(base); } +/// Writes stay inside the write root, the root itself is refused, and no temporary file is left outside. #[test] fn writes_go_only_into_the_write_root_and_leave_no_temp_file_outside() { let base = folders("write"); - let (out, t) = run( - &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + let out = s(&base.join("out")); + let (out_run, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &out], &[ ("open", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": s(&base.join("out/saved.dxf"))})), ("save", json!({"path": s(&base.join("outside/saved.dxf"))})), ("save", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": format!("{}/../outside/up.dxf", s(&base.join("out")))})), + ("save", json!({"path": out})), + ("save", json!({"path": format!("{out}/../out")})), ("execute", json!({"command": "export", "params": {"path": s(&base.join("out/art.png")), "format": "png"}})), ("execute", json!({"command": "export", "params": {"path": s(&base.join("outside/art.png")), "format": "png"}})), ("render", json!({"path": s(&base.join("out/view.png"))})), @@ -122,20 +132,22 @@ fn writes_go_only_into_the_write_root_and_leave_no_temp_file_outside() { ("execute", json!({"command": "circle", "params": {"center": [0, 0], "radius": 1}})), ], ); - assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + assert!(out_run.status.success(), "stderr: {}", String::from_utf8_lossy(&out_run.stderr)); ok(&t[0]); ok(&t[1]); assert!(base.join("out/saved.dxf").is_file()); refused(&t[2], "outside the write root"); refused(&t[3], "outside the write root"); refused(&t[4], "outside the write root"); - ok(&t[5]); - assert!(base.join("out/art.png").is_file()); - refused(&t[6], "outside the write root"); + refused(&t[5], "the write root itself cannot be written"); + refused(&t[6], "the write root itself cannot be written"); ok(&t[7]); - assert!(base.join("out/view.png").is_file()); + assert!(base.join("out/art.png").is_file()); refused(&t[8], "outside the write root"); ok(&t[9]); + assert!(base.join("out/view.png").is_file()); + refused(&t[10], "outside the write root"); + ok(&t[11]); assert!(!base.join("outside/saved.dxf").exists()); assert!(!base.join("outside/art.png").exists()); @@ -143,12 +155,17 @@ fn writes_go_only_into_the_write_root_and_leave_no_temp_file_outside() { // The save's temporary file is beside the destination, inside the root; none is outside. assert!(!base.join("outside/saved.dxf.cadcraft-tmp").exists()); assert!(!base.join("outside/up.dxf.cadcraft-tmp").exists()); + assert!(!base.join("out.cadcraft-tmp").exists(), "writing to the root must not leave its temporary file beside it"); let leftovers: Vec = std::fs::read_dir(base.join("outside")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); assert_eq!(leftovers, ["b.dxf"], "nothing was written outside the roots"); + let temps: Vec = + std::fs::read_dir(&base).unwrap().filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| n.ends_with(".cadcraft-tmp")).collect(); + assert!(temps.is_empty(), "no temporary file beside or outside the roots: {temps:?}"); let _ = std::fs::remove_dir_all(base); } +/// A root left out grants none of its own access: a read root allows no writes, while a write root also allows reads. #[test] fn a_root_left_out_grants_none_of_its_access() { let base = folders("left-out"); @@ -164,12 +181,63 @@ fn a_root_left_out_grants_none_of_its_access() { let (out, t) = run( &["--automation-write-root", &s(&base.join("out"))], - &[("open", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": s(&base.join("out/new.dxf"))}))], + &[ + ("open", json!({"path": s(&base.join("in/a.dxf"))})), + ("save", json!({"path": s(&base.join("out/new.dxf"))})), + // Reads are allowed under the write root: the agent can reopen what it saved. + ("open", json!({"path": s(&base.join("out/new.dxf"))})), + ], ); assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); - refused(&t[0], "read authority is absent"); + refused(&t[0], "outside the read root (or the write root)"); ok(&t[1]); assert!(base.join("out/new.dxf").is_file()); + ok(&t[2]); + let _ = std::fs::remove_dir_all(base); +} + +/// The shared plotter settings folder is outside the roots: every action refuses and it is unchanged. +#[test] +fn plotter_settings_outside_the_roots_are_refused() { + let base = folders("plotters"); + let config = base.join("config"); + let settings = config.join("plotters"); + std::fs::create_dir_all(&settings).unwrap(); + let device = cadcraft_engine::doc::PlotterConfig { + name: "Office".into(), + description: "not the agent's".into(), + papers: vec![cadcraft_engine::doc::DevicePaper { name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] }], + ..Default::default() + }; + let file = settings.join("Office.plotter.json"); + let original = device.to_file_text(); + std::fs::write(&file, &original).unwrap(); + + let text = original.clone(); + let (out, t) = run_env( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[ + ("execute", json!({"command": "plottermanager", "params": {}})), + ("execute", json!({"command": "plottermanager", "params": {"action": "get", "name": "Office"}})), + ("execute", json!({"command": "plottermanager", "params": {"action": "new", "name": "Leak", "output": "pdf"}})), + ("execute", json!({"command": "plottermanager", "params": {"action": "set", "name": "Office", "description": "changed"}})), + ("execute", json!({"command": "plottermanager", "params": {"action": "load", "text": text, "name": "Leaked Copy"}})), + ("execute", json!({"command": "plottermanager", "params": {"action": "delete", "name": "Office"}})), + ], + &[("CADCRAFT_CONFIG_DIR", &s(&config))], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + refused(&t[0], "outside the read root (or the write root)"); + refused(&t[1], "unknown plotter"); + refused(&t[2], "outside the write root"); + refused(&t[3], "unknown plotter"); + refused(&t[4], "outside the write root"); + refused(&t[5], "unknown plotter"); + + assert_eq!(std::fs::read_to_string(&file).unwrap(), original, "the shared file is unchanged"); + let names: Vec = std::fs::read_dir(&settings).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["Office.plotter.json"], "nothing was created or deleted in the settings folder"); + assert!(!settings.join("Office.plotter.json.cadcraft-tmp").exists()); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index d5f7382338..fce04acfe7 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -77,9 +77,27 @@ impl PlotterStore { } Ok(dir()?.join(n)) } + /// Refuse a settings path automation may not read (always allowed without roots). + fn check_read(path: &std::path::Path) -> std::result::Result<(), String> { + if crate::file_access::current().is_none() { + return Ok(()); + } + let path = path.to_str().ok_or_else(|| "the plotter settings path is not valid UTF-8".to_string())?; + crate::file_access::check_read(path) + } + /// Refuse a settings path automation may not write (always allowed without roots). + fn check_write(path: &std::path::Path) -> std::result::Result<(), String> { + if crate::file_access::current().is_none() { + return Ok(()); + } + let path = path.to_str().ok_or_else(|| "the plotter settings path is not valid UTF-8".to_string())?; + crate::file_access::check_write(path) + } PlotterStore { list: || { - let rd = match std::fs::read_dir(dir()?) { + let d = dir()?; + check_read(&d)?; + let rd = match std::fs::read_dir(d) { Ok(rd) => rd, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), Err(e) => return Err(e.to_string()), @@ -92,6 +110,7 @@ impl PlotterStore { }, read: |n| { let p = file(n)?; + check_read(&p)?; let len = std::fs::metadata(&p).map_err(|e| format!("{n}: {e}"))?.len(); if len > cadcraft_doc::MAX_PLOTTER_FILE as u64 { return Err(format!("{n}: the plotter configuration file is too large")); @@ -100,10 +119,16 @@ impl PlotterStore { }, write: |n, t| { let p = file(n)?; + // Checked before the folder it lives in is created. The temporary file sits beside it. + check_write(&p)?; std::fs::create_dir_all(dir()?).map_err(|e| e.to_string())?; crate::atomic_write::write_atomic(&p, t.as_bytes()).map_err(|e| format!("{n}: {e}")) }, - delete: |n| std::fs::remove_file(file(n)?).map_err(|e| format!("{n}: {e}")), + delete: |n| { + let p = file(n)?; + check_write(&p)?; + std::fs::remove_file(p).map_err(|e| format!("{n}: {e}")) + }, } } } @@ -513,7 +538,11 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result { let cmd = "plottermanager"; let action = str_param(p, "action").unwrap_or("list").trim().to_ascii_lowercase(); match action.as_str() { - "list" => Ok(json!({ "devices": devices().iter().map(summary).collect::>() })), + "list" => { + // A refused settings folder is an error, not a short list: show the refusal. + (store().list)().map_err(|e| bad(cmd, e))?; + Ok(json!({ "devices": devices().iter().map(summary).collect::>() })) + } "get" => { let n = device_name(cmd, p)?; let c = find_device(&n).ok_or_else(|| unknown_device(cmd, &n))?; diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 78e237ad4a..35ed5f9ec1 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -11,8 +11,9 @@ //! is a link that leads nowhere). //! - The result must lie inside the root, compared by whole components (`/work2` isn't inside //! `/work`), without regard to case on Windows. -//! - Read and write access are separate: a root given alone grants only its own kind of access. -//! A root left out grants none of that access. +//! - Reads may lie under either root; writes only under the write root, and never at the write +//! root itself (its save-style temporary file would be outside). A root given alone grants +//! reads under it even when it is the write root; a read root grants no writes. //! //! Roots are in force on a thread inside [`confine`]. The MCP headless backend runs every call in //! it; without roots nothing is checked, so the app and the command line keep working everywhere. @@ -85,25 +86,33 @@ impl AutomationRoots { } /// May the file or folder at `path` be read (or written)? `Err` says why not. + /// + /// A read may lie under either root: the read root, or the write root (files the agent may + /// write it may also read back). A write may lie only under the write root, and not at the + /// root itself, whose save-style temporary file would sit beside it. pub fn check(&self, path: &str, access: Access) -> Result<(), String> { - let root = match access { - Access::Read => self.read.as_ref(), - Access::Write => self.write.as_ref(), - }; - let Some(Root { resolved: folder, shown }) = root else { - return match access { - Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")), - Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")), - }; + let target = resolve(path)?; + if access == Access::Read { + let roots = [self.read.as_ref(), self.write.as_ref()]; + if roots.iter().flatten().any(|r| inside(&target, &r.resolved)) { + return Ok(()); + } + if roots.iter().all(|r| r.is_none()) { + return Err(format!("automation filesystem access is not granted: read authority is absent: {path}")); + } + return Err(format!("automation path rejected: outside the read root (or the write root): {path}")); + } + let Some(Root { resolved: folder, shown }) = self.write.as_ref() else { + return Err(format!("automation filesystem access is not granted: write authority is absent: {path}")); }; - if inside(&resolve(path)?, folder) { - return Ok(()); + if !inside(&target, folder) { + return Err(format!("automation path rejected: outside the write root {}: {path}", shown.display())); } - let root = shown.display(); - match access { - Access::Read => Err(format!("automation path rejected: outside the read root {root}: {path}")), - Access::Write => Err(format!("automation path rejected: outside the write root {root}: {path}")), + // A write to the root itself would put its temporary file beside the root, outside it. + if same(&target, folder) { + return Err(format!("automation path rejected: the write root itself cannot be written: {path}")); } + Ok(()) } } @@ -196,6 +205,11 @@ fn inside(path: &Path, root: &Path) -> bool { root.components().all(|r| path.next().is_some_and(|p| same_component(p, r))) } +/// Is `path` (resolved) exactly `root`, compared like [`inside`] does? +fn same(path: &Path, root: &Path) -> bool { + path.components().count() == root.components().count() && path.components().zip(root.components()).all(|(p, r)| same_component(p, r)) +} + fn same_component(a: Component, b: Component) -> bool { if a == b { return true; @@ -233,10 +247,12 @@ mod tests { (base, roots) } + /// `p` as a string a command would pass. fn s(p: PathBuf) -> String { p.to_string_lossy().into_owned() } + /// Paths under either root may be read; writes stay inside the write root. #[test] fn paths_inside_the_roots_pass_and_others_dont() { let (base, roots) = folders("inside"); @@ -246,10 +262,39 @@ mod tests { assert_eq!(roots.check(&s(base.join("out/new/deeper/x.png")), Access::Write), Ok(()), "and by their nearest folder"); let e = roots.check(&s(base.join("outside/secret.dxf")), Access::Read).unwrap_err(); assert!(e.starts_with("automation path rejected: outside the read root"), "{e}"); - // Read and write access are separate. + // Reads are allowed under the write root too; writes are not allowed under the read root. + assert_eq!(roots.check(&s(base.join("out/x.png")), Access::Read), Ok(()), "the write root also grants reads"); let e = roots.check(&s(base.join("in/a.dxf")), Access::Write).unwrap_err(); assert!(e.contains("outside the write root"), "{e}"); - assert!(roots.check(&s(base.join("out/x.png")), Access::Read).unwrap_err().contains("outside the read root")); + let _ = std::fs::remove_dir_all(base); + } + + /// A write-only root still permits reads inside it; reads outside both roots are refused. + #[test] + fn reads_are_allowed_under_either_root() { + let (base, _) = folders("either"); + let write_only = AutomationRoots::new(None, Some(&base.join("out"))).unwrap().unwrap(); + assert_eq!(write_only.check(&s(base.join("out/new.dxf")), Access::Read), Ok(()), "a file to read back"); + let e = write_only.check(&s(base.join("in/a.dxf")), Access::Read).unwrap_err(); + assert!(e.contains("outside the read root (or the write root)"), "{e}"); + let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); + assert_eq!(read_only.check(&s(base.join("in/a.dxf")), Access::Read), Ok(())); + assert!(read_only.check(&s(base.join("out/new.dxf")), Access::Read).is_err(), "a read root alone grants no read of another folder"); + let _ = std::fs::remove_dir_all(base); + } + + /// A write to the write root itself would put its `.cadcraft-tmp` file beside the root: refused. + #[test] + fn writing_to_the_write_root_itself_is_refused() { + let (base, roots) = folders("write-root"); + let out = s(base.join("out")); + let sep = std::path::MAIN_SEPARATOR; + for p in [out.clone(), format!("{out}{sep}."), format!("{out}{sep}..{sep}out")] { + let e = roots.check(&p, Access::Write).unwrap_err(); + assert!(e.contains("the write root itself cannot be written"), "{p}: {e}"); + } + assert_eq!(roots.check(&out, Access::Read), Ok(()), "reading the root stays allowed"); + assert_eq!(roots.check(&s(base.join("out/new/x.png")), Access::Write), Ok(()), "a normal save inside still works"); let _ = std::fs::remove_dir_all(base); } diff --git a/docs/mcp.md b/docs/mcp.md index fa76d3452c..7b64dffa57 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -41,17 +41,19 @@ cadcraft-cli mcp --automation-read-root /work/project --automation-write-root /w The two flags (PhotoCraft, VectorCraft and the other Craft apps take the same ones, so one client configuration works across the suite) keep the agent to the folders you give it: -- Every file a command **reads** must lie inside the **read root**: `open`, `recover`, `compare`, - `script`, `import`, `insert`, `xattach` and every xref it loads, `new` templates, `appload` and - LISP `load`/`open`, support files (`linetype`, `hatch.patterns`, `aliasedit`, `reinit`), data - links, and plot style and plotter configuration files named by a path. +- Every file a command **reads** must lie inside the **read root or the write root**: `open`, + `recover`, `compare`, `script`, `import`, `insert`, `xattach` and every xref it loads, `new` + templates, `appload` and LISP `load`/`open`, support files (`linetype`, `hatch.patterns`, + `aliasedit`, `reinit`), data links, plot style and plotter configuration files named by a path, + and the shared plotter settings folder. - Every file a command **writes** must lie inside the **write root**: `save`/`qsave`/`saveas` (including the temporary file written beside the destination), `export`, `plot`, `publish`, - `pdfbook`, `wblock`, data extraction, table export, plot style and plotter saves, and - `render {path}`. -- Read and write access are separate. Give the same folder twice for both; a root left out grants - none of its access (with only `--automation-read-root`, nothing can be written to disk). Without - either flag nothing changes. + `pdfbook`, `wblock`, data extraction, table export, plot style and plotter saves, the shared + plotter settings folder, and `render {path}`. The write root itself is refused: a save's + temporary file would sit beside it, outside the root. +- Give the same folder twice for both. A root left out grants none of its *own* access: a read + root allows no writes, while a write root still allows reads inside it (files the agent wrote it + can read back). Without either flag nothing changes. - A path is made absolute against the server's working directory, then its links are followed: a file or folder link that leads out of a root is outside it. For a file that doesn't exist yet, its nearest existing folder's links are followed and the rest must be plain names, so `..` below @@ -61,8 +63,10 @@ configuration works across the suite) keep the agent to the folders you give it: refused. - A refused path is an ordinary tool error with `isError: true` that the agent can read and correct, for example `automation path rejected: outside the write root - /work/project/out: /etc/x.png` or `automation filesystem access is not granted: write authority - is absent: /work/project/out/x.png`. + /work/project/out: /etc/x.png`, `automation path rejected: outside the read root (or the write + root): /etc/x.png`, `automation path rejected: the write root itself cannot be written: + /work/project/out`, or `automation filesystem access is not granted: write authority is absent: + /work/project/out/x.png`. - The roots must be existing folders; a missing one stops the server with an error. Each flag is given once (`--flag ` or `--flag=`). From f09c50d6b84d4590d7b38726cedab5e21318db12 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:56:13 +0530 Subject: [PATCH 03/27] mcp: refuse unclassified commands under the automation roots and walk the registry Bring the rest of the file access under the roots: - Image references had no check at all, and the loader threads lost the roots, which are per thread. Both are held to them now. - The xref and image search looked outside the roots before any check, listing folders and answering whether a file exists. It now skips those places. - setvar SAVEFILEPATH could point autosave and recovery anywhere, so it is refused under roots, and so is drawingrecovery. - A command runs under roots only if file_access/commands.rs classifies it. Anything else is refused, whichever route starts it. every_command_is_classified walks the registry for the table. mcp_roots_walk.rs walks it through the real server with paths outside the roots, seeing reads by access time and writes by metadata. The same walk with no roots is the control: it has to find the same commands escaping. Also drops two duplicated checks the rebase left in template.rs and compare.rs. --- apps/cadcraft-cli/tests/mcp_roots_walk.rs | 535 +++++++++++++++++++++ crates/engine/src/cmd/blocks/xref.rs | 3 + crates/engine/src/cmd/blocks/xref/load.rs | 20 +- crates/engine/src/cmd/file/compare.rs | 5 +- crates/engine/src/cmd/file/template.rs | 1 - crates/engine/src/cmd/image.rs | 19 +- crates/engine/src/file_access.rs | 2 + crates/engine/src/file_access/commands.rs | 537 ++++++++++++++++++++++ crates/engine/src/lisp/builtins/files.rs | 2 +- crates/engine/src/session/execute.rs | 3 + crates/engine/src/session/interactive.rs | 3 + crates/engine/src/sysvars.rs | 4 + docs/mcp.md | 14 +- 13 files changed, 1128 insertions(+), 20 deletions(-) create mode 100644 apps/cadcraft-cli/tests/mcp_roots_walk.rs create mode 100644 crates/engine/src/file_access/commands.rs diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs new file mode 100644 index 0000000000..cfe237a6eb --- /dev/null +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -0,0 +1,535 @@ +//! Walks every command in the registry through the real MCP server with paths outside the +//! automation roots (#1472). Reads show as a changed access time and writes as a changed size, +//! modification time or folder, whatever the command does with the path. The same walk without +//! roots has to find escapes, or finding none under roots would prove nothing. +#![cfg(unix)] +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Never crash). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::{File, FileTimes}; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc::{Receiver, channel}; +use std::time::{Duration, SystemTime}; + +use serde_json::{Value, json}; + +/// Longest a call may take before the server counts as hung. +const CALL_TIMEOUT: Duration = Duration::from_secs(60); +/// The extensions commands choose their behaviour by. +const EXTENSIONS: &[&str] = &["dxf", "dwg", "dwt", "scr", "lsp", "lin", "pat", "pgp", "csv", "txt", "png", "pdf", "svg", "ctb"]; +/// The parameter names a command might take a path under. +const PATH_KEYS: &[&str] = + &["path", "file", "template", "patternFile", "from", "to", "source", "target", "output", "folder", "dir", "filename", "document"]; +/// A valid 1x1 PNG. +const PNG: &[u8] = &[ + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 0x1F, 0x15, 0xC4, + 0x89, 0, 0, 0, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0, 1, 0, 0, 5, 0, 1, 0x0D, 0x0A, 0x2D, 0xB4, 0, 0, 0, 0, 0x49, 0x45, 0x4E, 0x44, + 0xAE, 0x42, 0x60, 0x82, +]; + +fn s(p: &Path) -> String { + p.to_string_lossy().into_owned() +} + +/// A running `cadcraft-cli mcp`. +struct Server { + child: Child, + stdin: ChildStdin, + replies: Receiver, + next: u64, +} + +impl Server { + fn start(args: &[String], cwd: &Path, config: &Path) -> Self { + let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) + .arg("mcp") + .args(args) + .current_dir(cwd) + .env("CADCRAFT_CONFIG_DIR", config) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn cadcraft-cli"); + let stdin = child.stdin.take().unwrap(); + let stdout = child.stdout.take().unwrap(); + let (tx, replies) = channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if let Ok(v) = serde_json::from_str::(&line) + && tx.send(v).is_err() + { + break; + } + } + }); + let mut server = Self { child, stdin, replies, next: 1 }; + server.request("initialize", json!({"protocolVersion": "2025-06-18"})).expect("initialize"); + server + } + + fn request(&mut self, method: &str, params: Value) -> Option { + let id = self.next; + self.next += 1; + let req = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}); + writeln!(self.stdin, "{req}").ok()?; + loop { + let reply = self.replies.recv_timeout(CALL_TIMEOUT).ok()?; + if reply["id"] == id { + return Some(reply); + } + } + } + + /// A tool's first text block, or `None` when the server hung or stopped. + fn tool(&mut self, name: &str, arguments: Value) -> Option { + let reply = self.request("tools/call", json!({"name": name, "arguments": arguments}))?; + Some(reply["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string()) + } + + fn execute(&mut self, command: &str, params: Value) -> Option { + self.tool("execute", json!({"command": command, "params": params})) + } +} + +impl Drop for Server { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// The folders of one walk: `in` and `out` are the roots, nothing under `outside` may be touched. +struct Fixture { + base: PathBuf, + outside: PathBuf, + /// Each path under `outside`, with its size, modification time and access time. + baseline: BTreeMap, + /// Whether this file system records reads at all (`noatime` doesn't). + sees_reads: bool, +} + +impl Fixture { + fn new(tag: &str) -> Self { + let base = std::env::temp_dir().join(format!("cc-walk-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["in", "out"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + let probe = base.join("probe"); + std::fs::write(&probe, "x").unwrap(); + age_access_time(&probe); + let before = std::fs::metadata(&probe).unwrap().accessed().unwrap(); + std::fs::read(&probe).unwrap(); + let sees_reads = std::fs::metadata(&probe).unwrap().accessed().unwrap() != before; + let outside = base.join("outside"); + let mut f = Self { base, outside, baseline: BTreeMap::new(), sees_reads }; + f.reset(); + f + } + + /// Lay out `outside` afresh and start watching it. + fn reset(&mut self) { + let o = self.outside.clone(); + let _ = std::fs::remove_dir_all(&o); + for d in ["cwd", "config/plotters", "recover"] { + std::fs::create_dir_all(o.join(d)).unwrap(); + } + let dxf = cadcraft_io::write(&cadcraft_engine::doc::Drawing::new_imperial(), "x.dxf").unwrap(); + for ext in EXTENSIONS { + let body: &[u8] = match *ext { + "dxf" | "dwg" | "dwt" => &dxf, + "scr" => b"CIRCLE 0,0 5\n", + "lsp" => b"(princ 1)\n", + "lin" => b"*WALK,walk\nA,1,-1\n", + "pat" => b"*WALK,walk\n0,0,0,0,1\n", + "pgp" => b"W,*LINE\n", + "csv" | "txt" => b"a,b\n1,2\n", + "png" => PNG, + _ => b"canary", + }; + std::fs::write(o.join(format!("canary.{ext}")), body).unwrap(); + } + // Two images, so that a drawing naming both loads them on threads of their own. + std::fs::write(o.join("second.png"), PNG).unwrap(); + let device = cadcraft_engine::doc::PlotterConfig { name: "Office".into(), ..Default::default() }; + std::fs::write(o.join("config/plotters/Office.plotter.json"), device.to_file_text()).unwrap(); + self.baseline.clear(); + for p in tree(&o) { + age_access_time(&p); + let m = std::fs::metadata(&p).unwrap(); + self.baseline.insert(p, (m.len(), m.modified().unwrap(), m.accessed().unwrap())); + } + } + + /// What happened under `outside` since [`Self::reset`]. Only metadata is read: this leaves + /// the access times as they are. + fn touched(&self) -> Vec { + let mut seen = Vec::new(); + for (p, (len, modified, accessed)) in &self.baseline { + let name = p.strip_prefix(&self.outside).unwrap().display(); + match std::fs::metadata(p) { + Err(_) => seen.push(format!("removed {name}")), + Ok(m) if m.modified().unwrap() != *modified || (!m.is_dir() && m.len() != *len) => seen.push(format!("wrote {name}")), + Ok(m) if self.sees_reads && m.accessed().unwrap() != *accessed => seen.push(format!("read {name}")), + Ok(_) => {} + } + } + seen + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.base); + } +} + +fn tree(dir: &Path) -> Vec { + let mut out = vec![dir.to_path_buf()]; + for e in std::fs::read_dir(dir).unwrap().flatten() { + if e.path().is_dir() { + out.extend(tree(&e.path())); + } else { + out.push(e.path()); + } + } + out +} + +/// Put `p`'s access time in the past, so that the next read updates it even under `relatime`. +fn age_access_time(p: &Path) { + let past = SystemTime::now() - Duration::from_secs(3 * 24 * 3600); + File::open(p).unwrap().set_times(FileTimes::new().set_accessed(past)).unwrap(); +} + +/// The `action` or `option` values a parameter doc lists: `action?: list|open|discard (…)`. +fn actions(doc: &str) -> Vec { + let mut out = Vec::new(); + for key in ["action", "option"] { + let Some(at) = doc.find(key) else { continue }; + let rest = doc[at + key.len()..].trim_start_matches(['?', ':', ' ']); + let end = rest.find([',', '}', '(']).unwrap_or(rest.len()); + out.extend(rest[..end].split('|').map(|w| w.trim().trim_matches('"').to_string()).filter(|w| !w.is_empty())); + } + out +} + +/// The calls to try for command `id`: every path-like key set to `target`, with each action. +fn variants(doc: &str, target: &str, handle: &str, table: &str) -> Vec { + let mut base = json!({"handle": table, "handles": [handle], "at": [0, 0], "name": "walk"}); + for key in PATH_KEYS { + base[*key] = json!(target); + } + let mut named = base.clone(); + named["name"] = json!(target); + let mut device = base.clone(); + device["name"] = json!("Office"); + // Commands refuse parameters that don't go together, so each key the doc names goes on its own too. + let lower = doc.to_ascii_lowercase(); + let documented = PATH_KEYS.iter().filter(|key| **key == "path" || lower.contains(&key.to_ascii_lowercase())); + let alone = documented.flat_map(|key| { + [ + json!({*key: target}), + json!({*key: target, "handles": [handle]}), + json!({*key: target, "handle": table}), + json!({*key: target, "name": "Office"}), + ] + }); + let mut out = Vec::new(); + for v in [base, named, device].into_iter().chain(alone) { + out.push(v.clone()); + for a in actions(doc) { + let mut with = v.clone(); + with["action"] = json!(a); + with["option"] = json!(a); + out.push(with); + } + } + out +} + +/// Whether a command's doc says it takes a file. These get every extension; the rest, one. +fn takes_a_file(doc: &str) -> bool { + let d = doc.to_ascii_lowercase(); + ["path", "file", "template", "folder", "action", "option"].iter().any(|w| d.contains(w)) +} + +/// A fresh drawing with a circle and a table, selected; the circle's and table's handles. +fn seed(server: &mut Server) -> Option<(String, String)> { + // Closed first: the walk starts tens of thousands of drawings, and they would all stay open. + server.execute("closeall", json!({}))?; + server.execute("new", json!({}))?; + let handle_of = |text: &str| serde_json::from_str::(text).ok().and_then(|v| v["handle"].as_str().map(str::to_string)).unwrap_or_default(); + let circle = server.execute("circle", json!({"center": [0, 0], "radius": 1}))?; + let table = server.execute("table", json!({"at": [5, 5], "rows": 2, "columns": 2}))?; + server.execute("selectall", json!({}))?; + Some((handle_of(&circle), handle_of(&table))) +} + +/// What one walk saw. +struct Walk { + /// The command and the call that touched each file outside. + escapes: BTreeMap>, + calls: usize, + commands: usize, + /// Calls that hung or stopped the server. + lost: Vec, + sees_reads: bool, +} + +/// Run the walk, under `in` and `out` as roots or with no roots at all. +fn walk(tag: &str, roots: bool) -> Walk { + let mut f = Fixture::new(tag); + let args = if roots { + vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))] + } else { + vec![] + }; + let cwd = f.outside.join("cwd"); + let config = f.outside.join("config"); + let start = |f: &mut Fixture| { + let server = Server::start(&args, &cwd, &config); + f.reset(); + server + }; + let mut server = start(&mut f); + let listed = server.tool("list_commands", json!({})).expect("list_commands"); + let specs: Vec = serde_json::from_str(&listed).expect("the command list"); + assert!(specs.len() > 400, "the walk has to see the registry: {} commands", specs.len()); + let mut result = Walk { escapes: BTreeMap::new(), calls: 0, commands: specs.len(), lost: Vec::new(), sees_reads: f.sees_reads }; + + let mut steps: Vec<(String, Value)> = Vec::new(); + let o = f.outside.clone(); + let canary = |ext: &str| s(&o.join(format!("canary.{ext}"))); + let (circle, table) = seed(&mut server).expect("seed"); + assert!(!table.is_empty(), "the seed table has no handle"); + for spec in &specs { + let id = spec["id"].as_str().unwrap().to_string(); + let doc = spec["params"].as_str().unwrap_or_default(); + let mut targets: Vec = if takes_a_file(doc) { EXTENSIONS.iter().map(|e| canary(e)).collect() } else { vec![canary("dxf")] }; + if takes_a_file(doc) { + // A file that isn't there yet, in a folder that isn't there yet, and a relative path. + targets.extend(["dxf", "png", "pdf", "csv"].iter().map(|e| s(&o.join(format!("fresh/x.{e}"))))); + targets.push("../canary.dxf".to_string()); + } + for target in targets { + for v in variants(doc, &target, &circle, &table) { + steps.push((id.clone(), v)); + } + } + } + + let run_step = + |server: &mut Server, f: &mut Fixture, result: &mut Walk, id: &str, label: String, call: &mut dyn FnMut(&mut Server) -> Option| { + result.calls += 1; + let done = call(server); + let touched = f.touched(); + if !touched.is_empty() { + for what in touched { + result.escapes.entry(id.to_string()).or_default().push(format!("{what}: {label}")); + } + } + if done.is_none() { + result.lost.push(format!("{id}: {label}")); + } + done.is_some() + }; + + for (id, params) in &steps { + let label = params.to_string(); + let params = params.clone(); + let alive = run_step(&mut server, &mut f, &mut result, id, label, &mut |sv| sv.execute(id, params.clone())); + let dirty = !f.touched().is_empty(); + if !alive { + server = start(&mut f); + } else if dirty { + f.reset(); + } + // A command can stop the server without its own reply being lost. + if seed(&mut server).is_none() { + result.lost.push(format!("after {id}: {params}")); + server = start(&mut f); + seed(&mut server); + } + } + + // The ways in that aren't one command with a path parameter. + let dxf = canary("dxf"); + let png = canary("png"); + let scr = canary("scr"); + let lsp = canary("lsp"); + let tools: Vec<(&str, &str, Value)> = vec![ + ("tool:open", "open", json!({"path": dxf})), + ("tool:save", "save", json!({"path": dxf})), + ("tool:save-new", "save", json!({"path": s(&o.join("fresh/y.dxf"))})), + ("tool:render", "render", json!({"path": png})), + ("tool:command_line", "command_line", json!({"text": format!("SCRIPT {scr}")})), + ("tool:command_line", "command_line", json!({"text": format!("OPEN {dxf}")})), + ("tool:command_line", "command_line", json!({"text": format!("SAVEAS {dxf}")})), + ("tool:script", "script", json!({"text": format!("OPEN {dxf}\n")})), + ]; + for (label, name, a) in tools { + let text = a.to_string(); + let a = a.clone(); + let alive = run_step(&mut server, &mut f, &mut result, label, text, &mut |sv| sv.tool(name, a.clone())); + if alive { + f.reset(); + } else { + server = start(&mut f); + } + seed(&mut server); + } + let lisp = [ + format!("(setq f (open {dxf:?} \"r\")) (read-line f) (close f)"), + format!("(setq f (open {dxf:?} \"w\")) (write-line \"x\" f) (close f)"), + format!("(setq f (open {:?} \"w\")) (write-line \"x\" f) (close f)", s(&o.join("new.txt"))), + format!("(load {lsp:?})"), + ]; + for code in lisp { + let label = code.clone(); + run_step(&mut server, &mut f, &mut result, "lisp:code", label, &mut |sv| sv.execute("lisp", json!({"code": code}))); + f.reset(); + seed(&mut server); + } + // Settings that name a file or a folder, then the commands that use them. + let chained: Vec<(&str, Vec<(&str, Value)>)> = vec![ + ( + "stylesmanager", + vec![ + ("stylesmanager", json!({"action": "new", "name": "walk.ctb"})), + ("stylesmanager", json!({"action": "save", "name": "walk.ctb", "path": canary("ctb")})), + ("stylesmanager", json!({"action": "load", "path": canary("ctb")})), + ], + ), + ( + "pdfbook", + vec![("pline", json!({"points": [[0, 0], [210, 0], [210, 297], [0, 297]], "closed": true})), ("pdfbook", json!({"path": canary("pdf")}))], + ), + ("setvar:SAVEFILEPATH", vec![("setvar", json!({"name": "SAVEFILEPATH", "value": s(&o.join("recover"))})), ("drawingrecovery", json!({}))]), + ("setvar:QNEWTEMPLATE", vec![("setvar", json!({"name": "QNEWTEMPLATE", "value": dxf})), ("new", json!({}))]), + ]; + for (label, calls) in chained { + for (id, params) in calls { + run_step(&mut server, &mut f, &mut result, label, format!("{id} {params}"), &mut |sv| sv.execute(id, params.clone())); + } + f.reset(); + seed(&mut server); + } + result +} + +fn summary(w: &Walk) -> String { + format!( + "{} commands, {} calls, reads seen: {}, {} commands touched files outside, {} calls lost the server", + w.commands, + w.calls, + w.sees_reads, + w.escapes.len(), + w.lost.len() + ) +} + +/// Under roots, nothing in the registry reaches a file outside them. +#[test] +fn no_command_escapes_the_roots() { + let w = walk("roots", true); + println!("under roots: {}", summary(&w)); + let found: Vec = w.escapes.iter().flat_map(|(id, what)| what.iter().take(3).map(move |l| format!("{id}: {l}"))).collect(); + assert!(found.is_empty(), "escapes under the roots:\n{}", found.join("\n")); + assert!(w.lost.is_empty(), "calls that lost the server: {:?}", w.lost); +} + +/// The control: without roots the same walk finds these commands reaching the same files. If this +/// fails, the walk has stopped reaching them and [`no_command_escapes_the_roots`] proves nothing. +#[test] +fn the_walk_finds_escapes_without_roots() { + let w = walk("control", false); + println!("without roots: {}", summary(&w)); + let found: BTreeSet<&str> = w.escapes.keys().map(String::as_str).collect(); + println!("touched files outside: {}", found.iter().copied().collect::>().join(" ")); + let writers = [ + "saveas", + "export", + "plot", + "exportpdf", + "publish", + "pdfbook", + "wblock", + "-wblock", + "layout.saveas", + "layout", + "stylesmanager", + "plottermanager", + "tableexport", + "dataextraction", + "tool:save", + "tool:save-new", + "tool:render", + "lisp:code", + ]; + for id in writers { + assert!(found.contains(id), "the walk no longer finds `{id}` writing outside: {found:?}"); + } + if w.sees_reads { + for id in [ + "open", + "new", + "recover", + "script", + "import", + "insert", + "minsert", + "xattach", + "-xref", + "compare", + "imageattach", + "attach", + "aliasedit", + "linetype", + "hatch.patterns", + "appload", + "datalink", + "tool:open", + "setvar:QNEWTEMPLATE", + "setvar:SAVEFILEPATH", + ] { + assert!(found.contains(id), "the walk no longer finds `{id}` reading outside: {found:?}"); + } + } +} + +/// A drawing inside the roots can't bring in what it names outside them: an image or an xref saved +/// with a path outside stays unloaded, and nothing outside is read. +#[test] +fn a_drawing_cannot_reach_files_it_names_outside_the_roots() { + let mut f = Fixture::new("named"); + let host = f.base.join("in/host.dxf"); + { + // Made without roots: a drawing someone hands the agent. + let mut free = Server::start(&[], &f.outside.join("cwd"), &f.outside.join("config")); + free.execute("new", json!({})).unwrap(); + let image = free.execute("imageattach", json!({"path": s(&f.outside.join("canary.png"))})).unwrap(); + assert!(image.contains("handle"), "the image attaches: {image}"); + let second = free.execute("imageattach", json!({"path": s(&f.outside.join("second.png"))})).unwrap(); + assert!(second.contains("handle"), "the second image attaches: {second}"); + let xref = free.execute("xattach", json!({"path": s(&f.outside.join("canary.dxf")), "name": "walk"})).unwrap(); + assert!(xref.contains("handle"), "the xref attaches: {xref}"); + free.execute("saveas", json!({"path": s(&host)})).unwrap(); + } + let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))]; + let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config")); + f.reset(); + let opened = server.tool("open", json!({"path": s(&host)})).unwrap(); + let images = server.execute("image", json!({})).unwrap(); + let xrefs = server.execute("xref", json!({})).unwrap(); + server.tool("render", json!({})).unwrap(); + let touched = f.touched(); + assert!(touched.is_empty(), "{touched:?}\nopen: {opened}\nimage: {images}\nxref: {xrefs}"); + assert!(images.contains("canary.png") && !images.contains("\"Loaded\""), "the image stays unloaded: {images}"); + assert!(images.contains("\"foundAt\": null") || images.contains("\"foundAt\":null"), "and it isn't said to exist: {images}"); + assert!(!xrefs.contains("\"Loaded\""), "the xref stays unloaded: {xrefs}"); +} diff --git a/crates/engine/src/cmd/blocks/xref.rs b/crates/engine/src/cmd/blocks/xref.rs index 18da7fa0fa..602d43b176 100644 --- a/crates/engine/src/cmd/blocks/xref.rs +++ b/crates/engine/src/cmd/blocks/xref.rs @@ -374,6 +374,9 @@ fn run_xopen(s: &mut Session, p: &Value) -> Result { let file = load::find(&path, host.as_deref().map(std::path::Path::new), false).map_err(|m| match m { load::Missing::NotFound => bad("xopen", format!("{path}: file not found")), load::Missing::Refused(r) => bad("xopen", format!("{path}: not opened, {r}")), + load::Missing::OutsideRoots => { + bad("xopen", format!("{path}: not opened, automation path rejected: outside the read root (or the write root)")) + } })?; s.execute("open", &json!({ "path": file.to_string_lossy() })) } diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index 6522e8e180..5735f6699a 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -145,6 +145,8 @@ pub(crate) enum Missing { NotFound, /// The saved path isn't followed, and there is no file of its name beside the host. Refused(Refused), + /// The automation roots don't reach the file ([`crate::file_access`]). + OutsideRoots, } impl Missing { @@ -155,6 +157,9 @@ impl Missing { (XrefStatus::NotFound, format!("{path}: {why}")) } Self::Refused(r) => (XrefStatus::Unresolved, format!("{path}: not opened, {r}")), + Self::OutsideRoots => { + (XrefStatus::Unresolved, format!("{path}: not opened, automation path rejected: outside the read root (or the write root)")) + } } } } @@ -208,14 +213,17 @@ pub(crate) fn find(path: &str, host: Option<&Path>, chosen: bool) -> Result = files.into_iter().filter(allowed).collect(); + let outside = files.len() < looked_for; #[cfg(not(target_arch = "wasm32"))] - let found = files.iter().find(|p| p.is_file()).cloned().or_else(|| files.iter().find_map(|p| case_insensitive(p))); + let found = files.iter().find(|p| p.is_file()).cloned().or_else(|| files.iter().find_map(|p| case_insensitive(p))).filter(allowed); #[cfg(target_arch = "wasm32")] - let found: Option = { - let _ = files; - None - }; - found.ok_or(refused.map_or(Missing::NotFound, Missing::Refused)) + let found: Option = None; + found.ok_or(if outside { Missing::OutsideRoots } else { refused.map_or(Missing::NotFound, Missing::Refused) }) } /// Upper bound on directory entries scanned per path component by [`case_insensitive`]. diff --git a/crates/engine/src/cmd/file/compare.rs b/crates/engine/src/cmd/file/compare.rs index 3af713cd44..2b0b2678ad 100644 --- a/crates/engine/src/cmd/file/compare.rs +++ b/crates/engine/src/cmd/file/compare.rs @@ -111,10 +111,7 @@ fn read_path(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { crate::file_access::check_read(_path).map_err(|e| bad("compare", e))?; - { - crate::file_access::check_read(_path).map_err(|e| bad("compare", e))?; - std::fs::read(_path).map_err(|e| bad("compare", format!("{_path}: {e}"))) - } + std::fs::read(_path).map_err(|e| bad("compare", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] Err(bad("compare", "paths are not available on the web: open the other drawing and compare with it by name (`document`)")) diff --git a/crates/engine/src/cmd/file/template.rs b/crates/engine/src/cmd/file/template.rs index 7608eb1243..0134f2e9ff 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -74,7 +74,6 @@ fn read_template(path: &str) -> Result { #[cfg(not(target_arch = "wasm32"))] fn read_bytes(path: &str) -> Result> { - crate::file_access::check_read(path).map_err(|e| bad("new", e))?; crate::file_access::check_read(path).map_err(|e| bad("new", e))?; std::fs::read(path).map_err(|e| bad("new", format!("template {path}: {e}"))) } diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index daf46557b8..7cc1eac3a0 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -75,6 +75,7 @@ fn read_file(path: &str, host: Option<&str>) -> std::result::Result, Str #[cfg(not(target_arch = "wasm32"))] { let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?; + crate::file_access::check_read(&file.to_string_lossy())?; let len = std::fs::metadata(&file).map_err(|e| e.to_string())?.len(); if len > MAX_IMAGE_BYTES { return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20)); @@ -180,14 +181,18 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec 1 { // Each loader takes the next file nobody has started. let next = AtomicUsize::new(0); + // The automation roots are per thread, so they go along with each loader. + let roots = crate::file_access::current(); let work = || { - let mut done = Vec::new(); - loop { - let index = next.fetch_add(1, Ordering::Relaxed); - let Some(path) = paths.get(index) else { break }; - done.push((index, load(path))); - } - done + crate::file_access::confine(roots.as_ref(), || { + let mut done = Vec::new(); + loop { + let index = next.fetch_add(1, Ordering::Relaxed); + let Some(path) = paths.get(index) else { break }; + done.push((index, load(path))); + } + done + }) }; let finished: Vec<_> = std::thread::scope(|scope| { let started: Vec<_> = (0..loaders).filter_map(|_| std::thread::Builder::new().spawn_scoped(scope, work).ok()).collect(); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 35ed5f9ec1..589866f16a 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -22,6 +22,8 @@ //! a link) can still win that race. The roots keep an agent to the files it was given; they don't //! guard against other programs on the computer. +pub mod commands; + use std::cell::RefCell; use std::ffi::OsString; use std::path::{Component, Path, PathBuf}; diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs new file mode 100644 index 0000000000..f2b673a826 --- /dev/null +++ b/crates/engine/src/file_access/commands.rs @@ -0,0 +1,537 @@ +//! Which commands automation may run while the automation roots are in force ([`super`]). +//! +//! The checks that hold a path to the roots sit where the file is touched, and a new command that +//! touches a file through a new route would get past them. So a command runs under the roots only +//! if it is listed here: anything else is refused, whatever it does. Adding a command to the +//! registry means adding it to one of these lists (`every_command_is_classified` says so). + +/// Commands that read or write files, each path held to the roots where the file is touched. +pub const FILES: &[&str] = &[ + "-linetype", + "-plottermanager", + "-wblock", + "-xref", + "aliasedit", + "appload", + "attach", + "audit", + "compare", + "compareexport", + "dataextraction", + "datalink", + "datalinkupdate", + "eattext", + "export", + "exportpdf", + "hatch", + "hatch.patterns", + "image", + "imageattach", + "import", + "insert", + "layout", + "layout.saveas", + "linetype", + "lisp", + "minsert", + "new", + "open", + "options", + "pagesetup", + "pdfbook", + "plot", + "plotstyle", + "plottermanager", + "preview", + "publish", + "qsave", + "recover", + "reinit", + "saveas", + "script", + "setvar", + "share", + "stylesmanager", + "tableexport", + "wblock", + "xattach", + "xbind", + "xopen", + "xref", +]; + +/// Commands that can't be held to the roots, and why. +pub const REFUSED: &[(&str, &str)] = &[("drawingrecovery", "it works on the autosave folder (SAVEFILEPATH), which is the server's own")]; + +/// Commands that touch no file. +pub const NO_FILES: &[&str] = &[ + "close", + "closeall", + "document.switch", + "document.bytes", + "u", + "undo", + "redo", + "mredo", + "cutclip", + "cutbase", + "copyclip", + "copybase", + "pasteclip", + "pasteblock", + "pasteorig", + "erase.selection", + "selectall", + "ai_deselect", + "select", + "qselect", + "qselect.info", + "selectsimilar", + "isolateobjects", + "hideobjects", + "unisolateobjects", + "zoom", + "zoom.realtime", + "zoom.dynamic", + "zoom.previous", + "zoom.window", + "zoom.in", + "zoom.out", + "zoom.all", + "zoom.extents", + "zoom.object", + "pan", + "pan.left", + "pan.right", + "pan.up", + "pan.down", + "regen", + "regenall", + "redraw", + "dview", + "view.set", + "view.get", + "layout.set", + "view", + "-vports", + "vports.activate", + "vports.named", + "line", + "pline", + "circle", + "arc", + "rectang", + "polygon", + "ellipse", + "point", + "point.multiple", + "xline", + "ray", + "spline", + "donut", + "solid", + "text", + "mtext", + "arc.sce", + "arc.sca", + "arc.scl", + "arc.sea", + "arc.sed", + "arc.ser", + "arc.cse", + "arc.csa", + "arc.csl", + "arc.continue", + "circle.cd", + "circle.2p", + "circle.3p", + "circle.ttr", + "circle.ttt", + "ellipse.axis", + "ellipse.arc", + "divide", + "measure", + "revcloud", + "revcloud.polygonal", + "revcloud.freehand", + "wipeout", + "3dpoly", + "helix", + "spline.cv", + "centermark", + "centerline", + "mline", + "mlstyle", + "mledit", + "breakline", + "dimlinear", + "dimaligned", + "dimradius", + "dimdiameter", + "dimangular", + "dimarc", + "dimordinate", + "dimcontinue", + "dimbaseline", + "qdim", + "dim", + "mleader", + "leader", + "dimstyle.update", + "dimoverride", + "dimreassociate", + "dimdisassociate", + "dimtedit.home", + "dimtedit.angle", + "dimtedit.left", + "dimtedit.center", + "dimtedit.right", + "dimtedit", + "dimspace", + "dimedit", + "dimedit.oblique", + "dimjogged", + "dimjogline", + "dimbreak", + "diminspect", + "mleaderedit", + "mleaderedit.add", + "mleaderedit.remove", + "mleaderalign", + "mleadercollect", + "scalelistedit", + "objectscale", + "aiobjectscaleadd", + "aiobjectscaleremove", + "annoreset", + "annoupdate", + "annovisible.current", + "annovisible.all", + "annovisible.toggle", + "gradient", + "boundary", + "region", + "hatchedit", + "hatchpick", + "overkill", + "block", + "-block", + "attdef", + "attedit", + "-attedit", + "base", + "blocks.dynamic", + "blocks.reference", + "blocks.reference.set", + "blocks.reference.grips", + "blocks.reference.grip", + "purge", + "blocks.list", + "battman", + "attdisp", + "attsync", + "burst", + "blockreplace", + "blocks.description", + "attdisp.normal", + "attdisp.on", + "attdisp.off", + "refedit", + "refset", + "refclose", + "bedit", + "bsave", + "bsaveas", + "bclose", + "erase", + "oops", + "move", + "copy", + "rotate", + "scale", + "mirror", + "stretch", + "offset", + "trim", + "extend", + "fillet", + "chamfer", + "explode", + "break", + "breakatpoint", + "join", + "draworder", + "draworder.front", + "draworder.back", + "draworder.above", + "draworder.under", + "texttofront", + "texttofront.text", + "texttofront.dimensions", + "texttofront.leaders", + "texttofront.all", + "hatchtoback", + "array", + "arrayrect", + "arraypolar", + "-array", + "arrayedit", + "arrayclose", + "pedit", + "splinedit", + "lengthen", + "align", + "blend", + "reverse", + "ncopy", + "mocoro", + "chspace", + "flatten", + "arraypath", + "textedit", + "group", + "ungroup", + "groupedit", + "groups.list", + "-group", + "pickstyle", + "grip.move", + "grip.stretch", + "grip.rotate", + "grip.scale", + "grip.mirror", + "grip.option", + "grip", + "compare.next", + "compare.previous", + "compareclose", + "layer", + "layer.new", + "layer.set", + "layer.current", + "layer.delete", + "laymcur", + "laymch", + "laycur", + "layiso", + "layuniso", + "layfrz", + "layoff", + "laylck", + "layulk", + "layon", + "laythw", + "layerp", + "layerstate.save", + "layerstate.restore", + "layerstate.list", + "layerstate.delete", + "layerstate.rename", + "laymrg", + "laydel", + "layout.new", + "layout.delete", + "layout.rename", + "layout.copy", + "layout.list", + "mview", + "mview.polygonal", + "vpclip", + "vports", + "vports.1", + "vports.2", + "vports.3", + "vports.4", + "viewport.set", + "vplayer", + "mspace", + "pspace", + "plotwindow", + "3dorbit", + "properties", + "properties.set", + "chprop", + "change", + "matchprop", + "color", + "lweight", + "ltscale", + "units", + "-units", + "thickness", + "limits", + "style", + "style.list", + "style.rename", + "style.delete", + "style.current", + "dimstyle", + "dimstyle.dimension", + "dimstyle.list", + "dimstyle.rename", + "dimstyle.delete", + "dimstyle.current", + "dimstyle.override", + "tablestyle", + "mleaderstyle", + "ddptype", + "rename", + "dist", + "id", + "list", + "area", + "time", + "status", + "drawing.inspect", + "entities", + "shapes", + "usage", + "loops", + "texts", + "countlist", + "counttable", + "count", + "union", + "subtract", + "intersect", + "massprop", + "ortho", + "grid", + "snap", + "polar", + "otrack", + "dynmode", + "lwdisplay", + "isodraft", + "isoplane", + "transparencydisplay", + "qpmode", + "selectioncycling", + "osnap", + "dsettings", + "getvar", + "sysvars", + "cal", + "quickcalc.pick", + "find", + "measuregeom", + "radius.measure", + "angle.measure", + "volume.measure", + "table", + "table.set", + "table.insertrow", + "table.deleterow", + "table.insertcol", + "table.deletecol", + "table.merge", + "table.unmerge", + "tablestyle.cellstyle", + "table.cellstyle", + "table.formula", + "table.recalc", + "tabledit", + "table.break", + "tolerance", + "txt2mtxt", + "geomconstraint", + "gccoincident", + "gcperpendicular", + "gcparallel", + "gctangent", + "gchorizontal", + "gcvertical", + "gccollinear", + "gcconcentric", + "gcsmooth", + "gcsymmetric", + "gcequal", + "gcfix", + "autoconstrain", + "constraintbar", + "constraintbar.showall", + "constraintbar.hideall", + "dimconstraint", + "dcaligned", + "dchorizontal", + "dcvertical", + "dcangular", + "dcradius", + "dcdiameter", + "dclinear", + "dcdisplay", + "dcdisplay.showall", + "dcdisplay.hideall", + "delconstraint", + "parameters", + "constraintsettings", + "constraintinfer", + "constraints.inspect", + "constraints.dof", +]; + +/// Why command `id` may not run here; `None` when it may. Without roots in force everything may. +pub fn refusal(id: &str) -> Option { + super::current()?; + if let Some((_, why)) = REFUSED.iter().find(|(c, _)| *c == id) { + return Some(format!("automation command refused: {why}")); + } + if FILES.contains(&id) || NO_FILES.contains(&id) { + return None; + } + Some("automation command refused: it is not classified for the automation roots".to_string()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::super::{AutomationRoots, confine}; + use super::*; + use std::collections::BTreeSet; + + /// Words in a command's parameter doc that usually name a file. In these commands they don't: + /// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a + /// direction. + const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"]; + + fn words(doc: &str) -> BTreeSet { + doc.to_ascii_lowercase().split(|c: char| !c.is_ascii_alphanumeric()).map(str::to_string).collect() + } + + /// Walks the registry: every command is on exactly one list, and the lists name no command + /// that is gone. A command whose parameters name a file can't be on the no-files list. + #[test] + fn every_command_is_classified() { + let refused: Vec<&str> = REFUSED.iter().map(|(c, _)| *c).collect(); + let lists = [FILES, refused.as_slice(), NO_FILES]; + let specs = crate::command_specs(); + for spec in specs { + let on = lists.iter().filter(|l| l.contains(&spec.id)).count(); + assert_eq!(on, 1, "`{}` is on {on} lists: add it to one in file_access/commands.rs", spec.id); + let doc = words(spec.params); + let names_a_file = ["path", "file", "template", "patternfile", "folder", "dir"].iter().any(|w| doc.contains(*w)); + if names_a_file && NO_FILES.contains(&spec.id) && !NOT_FILES.contains(&spec.id) { + panic!("`{}` takes a file ({}): it belongs on FILES, with its paths checked", spec.id, spec.params); + } + } + for id in lists.iter().flat_map(|l| l.iter()) { + assert!(specs.iter().any(|s| s.id == *id), "`{id}` is listed but no longer a command"); + } + } + + /// Under roots a command nobody classified is refused; without roots it isn't this table's business. + #[test] + fn an_unclassified_command_fails_closed() { + let base = std::env::temp_dir().join(format!("cc-commands-{}", std::process::id())); + std::fs::create_dir_all(&base).unwrap(); + let roots = AutomationRoots::new(Some(&base), None).unwrap(); + assert_eq!(refusal("made.up"), None); + confine(roots.as_ref(), || { + assert!(refusal("made.up").unwrap().contains("not classified")); + assert!(refusal("drawingrecovery").unwrap().contains("autosave")); + assert_eq!(refusal("open"), None); + assert_eq!(refusal("line"), None); + }); + let _ = std::fs::remove_dir_all(base); + } +} diff --git a/crates/engine/src/lisp/builtins/files.rs b/crates/engine/src/lisp/builtins/files.rs index 00c8788fab..1f19c71aff 100644 --- a/crates/engine/src/lisp/builtins/files.rs +++ b/crates/engine/src/lisp/builtins/files.rs @@ -32,7 +32,7 @@ pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec) -> Result } None => return Ok(Flow::Value(Value::Nil)), } - } else if !can_write(&path) || crate::file_access::check_write(&path).is_err() { + } else if crate::file_access::check_write(&path).is_err() || !can_write(&path) { return Ok(Flow::Value(Value::Nil)); } let id = ctx.env.next_file; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 230422e096..6f71b25372 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -26,6 +26,9 @@ impl Session { fn execute_guarded(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + if let Some(why) = crate::file_access::commands::refusal(spec.id) { + return Err(EngineError::Disabled(spec.id.into(), why)); + } (spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?; if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, spec.id) { return Err(EngineError::Disabled(spec.id.into(), why)); diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 273ce08902..dc1c30fb7b 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -39,6 +39,9 @@ impl Session { } return Err(EngineError::UnknownCommand(name.to_string())); }; + if let Some(why) = crate::file_access::commands::refusal(spec.id) { + return Err(EngineError::Disabled(spec.id.into(), why)); + } if transparent && spec.transparent && self.running.is_some() { // Transparent commands (zoom, pan…) run without cancelling the active one. if spec.interactive.is_none() { diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index e98836446d..0cd9020219 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -382,6 +382,10 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { "SAVETIME" => crate::autosave::set_savetime( as_f64(v).filter(|m| *m >= 0.0 && *m <= f64::from(crate::autosave::MAX_SAVETIME)).ok_or_else(bad)?.round() as u32, ), + // A folder autosave and recovery would use without any further check. + "SAVEFILEPATH" if crate::file_access::current().is_some() => { + return Err(EngineError::Other("SAVEFILEPATH cannot be changed under the automation roots".into())); + } "SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?), "ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?), // A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line). diff --git a/docs/mcp.md b/docs/mcp.md index 7b64dffa57..76ddba61e8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -47,7 +47,7 @@ configuration works across the suite) keep the agent to the folders you give it: `aliasedit`, `reinit`), data links, plot style and plotter configuration files named by a path, and the shared plotter settings folder. - Every file a command **writes** must lie inside the **write root**: `save`/`qsave`/`saveas` - (including the temporary file written beside the destination), `export`, `plot`, `publish`, + (including the temporary file and `.bak` written beside the destination), `export`, `plot`, `publish`, `pdfbook`, `wblock`, data extraction, table export, plot style and plotter saves, the shared plotter settings folder, and `render {path}`. The write root itself is refused: a save's temporary file would sit beside it, outside the root. @@ -67,6 +67,14 @@ configuration works across the suite) keep the agent to the folders you give it: root): /etc/x.png`, `automation path rejected: the write root itself cannot be written: /work/project/out`, or `automation filesystem access is not granted: write authority is absent: /work/project/out/x.png`. +- A file a drawing names is held to the roots too: an image or xref saved with a path outside them + stays unloaded, and the answer doesn't say whether the file exists. +- A command runs under the roots only if it is classified (`crates/engine/src/file_access/commands.rs`): + one nobody classified is refused, whatever it does. `drawingrecovery` is refused, and SAVEFILEPATH + can't be changed, because both work on the server's autosave folder. +- The server itself still reads the system's fonts, from the system font folders and + `CADCRAFT_SHXPATH`. Their paths come from the server's setup, never from the agent, but a font file + named by a drawing can decide which of them is read. - The roots must be existing folders; a missing one stops the server with an error. Each flag is given once (`--flag ` or `--flag=`). @@ -74,6 +82,10 @@ The flags confine the headless server. `--connect` with them is an error, since otherwise talk to an app that isn't confined; the app's control channel does not take them yet (#1585). Without `--connect` the server writes the files itself, so every check happens here. +A path is checked, then opened: another program on the computer that swaps in a link between the two +can still win that race, and a hard link can't be told from a file. Use the operating system's +sandbox as well if other programs can change these folders. + ## Tools | Tool | What it does | From 09e4f90740fec1a909a747061ebf83990495255c Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:52:13 +0530 Subject: [PATCH 04/27] Hold automation roots to exact names, the folder a name stands in, and every device name A case-sensitive Windows folder can hold Root beside root, so names are now compared exactly. The superscript COM and LPT ports and the NUL: form are device names too. A write must stand under the write root as well as lead there: a link outside pointing in had its .bak written beside it, and a plotter delete removed it. Paths reach the check as paths rather than as text, -WBLOCK no longer says whether a file outside the roots is there, and SHX fonts beside a drawing are not searched under the roots, since one can be a link leading out. --- apps/cadcraft-cli/tests/mcp_roots_walk.rs | 76 +++++++ crates/engine/src/cmd/audit.rs | 2 +- crates/engine/src/cmd/blocks/wblock.rs | 4 +- crates/engine/src/cmd/blocks/xref/load.rs | 4 +- crates/engine/src/cmd/file.rs | 4 +- crates/engine/src/cmd/image.rs | 2 +- crates/engine/src/cmd/plotters.rs | 30 +-- crates/engine/src/cmd/table/breaks.rs | 2 +- crates/engine/src/file_access.rs | 246 ++++++++++++++-------- crates/engine/src/file_access/commands.rs | 2 + crates/engine/src/lisp/builtins/files.rs | 2 +- crates/engine/tests/dash_wblock.rs | 19 ++ docs/mcp.md | 11 +- 13 files changed, 284 insertions(+), 120 deletions(-) diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index cfe237a6eb..784e5b005c 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -157,6 +157,12 @@ impl Fixture { std::fs::write(o.join("second.png"), PNG).unwrap(); let device = cadcraft_engine::doc::PlotterConfig { name: "Office".into(), ..Default::default() }; std::fs::write(o.join("config/plotters/Office.plotter.json"), device.to_file_text()).unwrap(); + self.watch(); + } + + /// Start watching what is under `outside` now. + fn watch(&mut self) { + let o = self.outside.clone(); self.baseline.clear(); for p in tree(&o) { age_access_time(&p); @@ -533,3 +539,73 @@ fn a_drawing_cannot_reach_files_it_names_outside_the_roots() { assert!(images.contains("\"foundAt\": null") || images.contains("\"foundAt\":null"), "and it isn't said to exist: {images}"); assert!(!xrefs.contains("\"Loaded\""), "the xref stays unloaded: {xrefs}"); } + +/// A font linked into the drawing's folder isn't read from where the link leads. +#[test] +fn a_font_linked_beside_a_drawing_is_not_followed_out() { + let mut f = Fixture::new("font"); + let host = f.base.join("in/host.dxf"); + { + let mut free = Server::start(&[], &f.outside.join("cwd"), &f.outside.join("config")); + free.execute("new", json!({})).unwrap(); + free.execute("style", json!({"name": "Walk", "font": "walkfont.shx"})).unwrap(); + free.execute("style.current", json!({"name": "Walk"})).unwrap(); + let text = free.execute("text", json!({"at": [0, 0], "height": 5, "text": "walk"})).unwrap(); + assert!(text.contains("handle"), "the text is drawn: {text}"); + free.execute("saveas", json!({"path": s(&host)})).unwrap(); + } + let saved = std::fs::read_to_string(&host).unwrap(); + assert!(saved.to_ascii_lowercase().contains("walkfont.shx"), "the drawing names the font"); + std::fs::write(f.outside.join("walkfont.shx"), b"AutoCAD-86 shapes 1.0").unwrap(); + std::os::unix::fs::symlink(f.outside.join("walkfont.shx"), f.base.join("in/walkfont.shx")).unwrap(); + let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))]; + let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config")); + f.reset(); + std::fs::write(f.outside.join("walkfont.shx"), b"AutoCAD-86 shapes 1.0").unwrap(); + f.watch(); + server.tool("open", json!({"path": s(&host)})).unwrap(); + server.tool("render", json!({})).unwrap(); + let touched = f.touched(); + assert!(touched.is_empty(), "{touched:?}"); +} + +/// Saving through a link that stands outside the roots and points in doesn't leave a backup +/// beside the link. +#[test] +fn a_backup_stays_inside_the_roots() { + let f = Fixture::new("backup"); + let target = f.base.join("out/t.dxf"); + std::fs::write(&target, cadcraft_io::write(&cadcraft_engine::doc::Drawing::new_imperial(), "x.dxf").unwrap()).unwrap(); + let link = f.outside.join("link.dxf"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))]; + let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config")); + server.tool("new_drawing", json!({})).unwrap(); + let saved = server.tool("save", json!({"path": s(&link)})).unwrap(); + assert!(saved.contains("outside the write root"), "{saved}"); + assert!(!f.outside.join("link.dxf.bak").exists() && !f.outside.join("link.bak").exists(), "{saved}"); +} + +/// Deleting a plotter acts on the entry in the settings folder, whatever it points at. +#[test] +fn a_plotter_link_outside_the_roots_is_not_removed() { + let f = Fixture::new("plotter"); + let inside = f.base.join("out/kept.plotter.json"); + std::fs::write(&inside, cadcraft_engine::doc::PlotterConfig { name: "Kept".into(), ..Default::default() }.to_file_text()).unwrap(); + let entry = f.outside.join("config/plotters/Kept.plotter.json"); + std::os::unix::fs::symlink(&inside, &entry).unwrap(); + let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))]; + let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config")); + let reply = server.execute("plottermanager", json!({"action": "delete", "name": "Kept"})).unwrap(); + assert!(std::fs::symlink_metadata(&entry).is_ok(), "the link is still there: {reply}"); +} + +/// Without roots, a settings folder that can't be read leaves the built-in devices listed. +#[test] +fn without_roots_an_unreadable_settings_folder_still_lists_devices() { + let f = Fixture::new("devices"); + let not_a_folder = f.outside.join("canary.txt"); + let mut server = Server::start(&[], &f.outside.join("cwd"), ¬_a_folder); + let list = server.execute("plottermanager", json!({"action": "list"})).unwrap(); + assert!(list.contains("devices"), "{list}"); +} diff --git a/crates/engine/src/cmd/audit.rs b/crates/engine/src/cmd/audit.rs index d7b2813b83..8167695986 100644 --- a/crates/engine/src/cmd/audit.rs +++ b/crates/engine/src/cmd/audit.rs @@ -143,7 +143,7 @@ fn write_audit_log(s: &Session, report: &crate::audit::Report) { // An unsaved drawing has no folder of its own to hold the log. let Some(path) = &path_str else { return }; let adt_path = std::path::PathBuf::from(path).with_extension("adt"); - if let Err(e) = crate::file_access::check_write(&adt_path.to_string_lossy()) { + if let Err(e) = crate::file_access::check_write(&adt_path) { log::warn!("AUDITCTL: not writing audit log {}: {e}", adt_path.display()); return; } diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs index 79b9955b26..ef3dc26099 100644 --- a/crates/engine/src/cmd/blocks/wblock.rs +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -172,7 +172,9 @@ fn output_path(typed: &str) -> String { fn exists(path: &str) -> bool { #[cfg(not(target_arch = "wasm32"))] { - std::path::Path::new(path).exists() + // Outside the automation roots the answer would say whether a file is there; the write + // that follows is refused anyway. + crate::file_access::check_write(path).is_ok() && std::path::Path::new(path).exists() } #[cfg(target_arch = "wasm32")] { diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index 5735f6699a..fe03b5d5d2 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -215,7 +215,7 @@ pub(crate) fn find(path: &str, host: Option<&Path>, chosen: bool) -> Result = files.into_iter().filter(allowed).collect(); let outside = files.len() < looked_for; @@ -269,7 +269,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { #[cfg(not(target_arch = "wasm32"))] { use std::io::Read; - crate::file_access::check_read(&file.to_string_lossy())?; + crate::file_access::check_read(file)?; let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes); let limit = MAX_XREF_BYTES.min(left); let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 2b298e8895..6892aa6176 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -337,7 +337,9 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result) -> std::result::Result, Str #[cfg(not(target_arch = "wasm32"))] { let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?; - crate::file_access::check_read(&file.to_string_lossy())?; + crate::file_access::check_read(&file)?; let len = std::fs::metadata(&file).map_err(|e| e.to_string())?.len(); if len > MAX_IMAGE_BYTES { return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20)); diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index fce04acfe7..6fa31e1202 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -77,26 +77,10 @@ impl PlotterStore { } Ok(dir()?.join(n)) } - /// Refuse a settings path automation may not read (always allowed without roots). - fn check_read(path: &std::path::Path) -> std::result::Result<(), String> { - if crate::file_access::current().is_none() { - return Ok(()); - } - let path = path.to_str().ok_or_else(|| "the plotter settings path is not valid UTF-8".to_string())?; - crate::file_access::check_read(path) - } - /// Refuse a settings path automation may not write (always allowed without roots). - fn check_write(path: &std::path::Path) -> std::result::Result<(), String> { - if crate::file_access::current().is_none() { - return Ok(()); - } - let path = path.to_str().ok_or_else(|| "the plotter settings path is not valid UTF-8".to_string())?; - crate::file_access::check_write(path) - } PlotterStore { list: || { let d = dir()?; - check_read(&d)?; + crate::file_access::check_read(&d)?; let rd = match std::fs::read_dir(d) { Ok(rd) => rd, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), @@ -110,7 +94,7 @@ impl PlotterStore { }, read: |n| { let p = file(n)?; - check_read(&p)?; + crate::file_access::check_read(&p)?; let len = std::fs::metadata(&p).map_err(|e| format!("{n}: {e}"))?.len(); if len > cadcraft_doc::MAX_PLOTTER_FILE as u64 { return Err(format!("{n}: the plotter configuration file is too large")); @@ -120,13 +104,13 @@ impl PlotterStore { write: |n, t| { let p = file(n)?; // Checked before the folder it lives in is created. The temporary file sits beside it. - check_write(&p)?; + crate::file_access::check_write(&p)?; std::fs::create_dir_all(dir()?).map_err(|e| e.to_string())?; crate::atomic_write::write_atomic(&p, t.as_bytes()).map_err(|e| format!("{n}: {e}")) }, delete: |n| { let p = file(n)?; - check_write(&p)?; + crate::file_access::check_write(&p)?; std::fs::remove_file(p).map_err(|e| format!("{n}: {e}")) }, } @@ -539,8 +523,10 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result { let action = str_param(p, "action").unwrap_or("list").trim().to_ascii_lowercase(); match action.as_str() { "list" => { - // A refused settings folder is an error, not a short list: show the refusal. - (store().list)().map_err(|e| bad(cmd, e))?; + // Under the roots a refused settings folder is an error, not a short list. + if crate::file_access::current().is_some() { + (store().list)().map_err(|e| bad(cmd, e))?; + } Ok(json!({ "devices": devices().iter().map(summary).collect::>() })) } "get" => { diff --git a/crates/engine/src/cmd/table/breaks.rs b/crates/engine/src/cmd/table/breaks.rs index 63504de55d..2cfadbaa70 100644 --- a/crates/engine/src/cmd/table/breaks.rs +++ b/crates/engine/src/cmd/table/breaks.rs @@ -238,7 +238,7 @@ fn read_link(id: &str, file: &std::path::Path) -> Result { let path = file.display(); #[cfg(not(target_arch = "wasm32"))] { - crate::file_access::check_read(&file.to_string_lossy()).map_err(|e| bad(id, e))?; + crate::file_access::check_read(file).map_err(|e| bad(id, e))?; let meta = std::fs::metadata(file).map_err(|e| bad(id, format!("{path}: {e}")))?; if meta.len() > MAX_LINK_BYTES { return Err(bad(id, format!("{path}: larger than {} MB", MAX_LINK_BYTES >> 20))); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 589866f16a..7e5bc285a5 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -10,7 +10,8 @@ //! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so //! is a link that leads nowhere). //! - The result must lie inside the root, compared by whole components (`/work2` isn't inside -//! `/work`), without regard to case on Windows. +//! `/work`) and exactly: both sides have been through the file system, which gives each folder +//! its real name, and a Windows folder can be case sensitive, with `Root` beside `root`. //! - Reads may lie under either root; writes only under the write root, and never at the write //! root itself (its save-style temporary file would be outside). A root given alone grants //! reads under it even when it is the write root; a read root grants no writes. @@ -39,30 +40,20 @@ pub enum Access { /// The folders automation may read and write; a root left out grants no access of its kind. #[derive(Debug)] pub struct AutomationRoots { - read: Option, - write: Option, + read: Option, + write: Option, } -#[derive(Debug)] -struct Root { - /// The folder made absolute, links followed: what paths are compared with. - resolved: PathBuf, - /// The same path, for people. - shown: PathBuf, -} - -impl Root { - /// The folder at `path`, which must exist. - fn open(path: &Path, access: Access) -> Result { - let kind = match access { - Access::Read => "read", - Access::Write => "write", - }; - let resolved = std::fs::canonicalize(path) - .and_then(|p| if p.is_dir() { Ok(p) } else { Err(std::io::ErrorKind::NotADirectory.into()) }) - .map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display()))?; - Ok(Self { shown: resolved.clone(), resolved }) - } +/// The folder at `path`, which must exist, made absolute with its links followed: what paths are +/// compared with. +fn open_root(path: &Path, access: Access) -> Result { + let kind = match access { + Access::Read => "read", + Access::Write => "write", + }; + std::fs::canonicalize(path) + .and_then(|p| if p.is_dir() { Ok(p) } else { Err(std::io::ErrorKind::NotADirectory.into()) }) + .map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display())) } impl AutomationRoots { @@ -72,31 +63,38 @@ impl AutomationRoots { if read.is_none() && write.is_none() { return Ok(None); } - let read = read.map(|p| Root::open(p, Access::Read)).transpose()?; - let write = write.map(|p| Root::open(p, Access::Write)).transpose()?; + let read = read.map(|p| open_root(p, Access::Read)).transpose()?; + let write = write.map(|p| open_root(p, Access::Write)).transpose()?; Ok(Some(Arc::new(Self { read, write }))) } /// The read root, absolute with its links followed. pub fn read_root(&self) -> Option<&Path> { - self.read.as_ref().map(|r| r.shown.as_path()) + self.read.as_deref() } /// The write root, absolute with its links followed. pub fn write_root(&self) -> Option<&Path> { - self.write.as_ref().map(|r| r.shown.as_path()) + self.write.as_deref() } /// May the file or folder at `path` be read (or written)? `Err` says why not. /// /// A read may lie under either root: the read root, or the write root (files the agent may /// write it may also read back). A write may lie only under the write root, and not at the - /// root itself, whose save-style temporary file would sit beside it. - pub fn check(&self, path: &str, access: Access) -> Result<(), String> { - let target = resolve(path)?; + /// root itself, whose save-style temporary file would sit beside it. Its name must stand there + /// too: a link outside pointing in is refused, since what is written beside the name (a + /// drawing's `.bak`) or done to it (a delete) happens in the folder that holds it. + /// + /// A path is taken as it is: turned into text on the way, a name that isn't text would name a + /// different file. + pub fn check(&self, given: impl AsRef, access: Access) -> Result<(), String> { + let given = given.as_ref(); + let target = resolve(given)?; + let path = given.display(); if access == Access::Read { let roots = [self.read.as_ref(), self.write.as_ref()]; - if roots.iter().flatten().any(|r| inside(&target, &r.resolved)) { + if roots.iter().flatten().any(|r| inside(&target, r)) { return Ok(()); } if roots.iter().all(|r| r.is_none()) { @@ -104,16 +102,19 @@ impl AutomationRoots { } return Err(format!("automation path rejected: outside the read root (or the write root): {path}")); } - let Some(Root { resolved: folder, shown }) = self.write.as_ref() else { + let Some(folder) = self.write.as_ref() else { return Err(format!("automation filesystem access is not granted: write authority is absent: {path}")); }; if !inside(&target, folder) { - return Err(format!("automation path rejected: outside the write root {}: {path}", shown.display())); + return Err(format!("automation path rejected: outside the write root {}: {path}", folder.display())); } // A write to the root itself would put its temporary file beside the root, outside it. if same(&target, folder) { return Err(format!("automation path rejected: the write root itself cannot be written: {path}")); } + if !inside(&resolve(given.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")))?, folder) { + return Err(format!("automation path rejected: stands outside the write root {}: {path}", folder.display())); + } Ok(()) } } @@ -145,26 +146,27 @@ pub fn current() -> Option> { } /// May `path` be read here? Always, without roots in force. -pub fn check_read(path: &str) -> Result<(), String> { +pub fn check_read(path: impl AsRef) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Read)) } /// May `path` be written here? Always, without roots in force. -pub fn check_write(path: &str) -> Result<(), String> { +pub fn check_write(path: impl AsRef) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Write)) } /// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest /// existing folder's links followed and the rest appended. -fn resolve(path: &str) -> Result { - if path.is_empty() { +fn resolve(path: &Path) -> Result { + let shown = path.display(); + if path.as_os_str().is_empty() { return Err("automation path rejected: path is empty".into()); } // Checked as given: making `…\NUL` absolute gives the device path `\\.\NUL` on Windows. - if cfg!(windows) && Path::new(path).components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) { - return Err(format!("automation path rejected: reserved device names are not allowed: {path}")); + if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if n.to_str().is_some_and(is_device_name))) { + return Err(format!("automation path rejected: reserved device names are not allowed: {shown}")); } - let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {path}: {e}"))?; + let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))?; // The names below the nearest existing folder, last first. let mut missing: Vec = vec![]; let mut at = absolute.as_path(); @@ -175,11 +177,11 @@ fn resolve(path: &str) -> Result { return Ok(found); } Err(e) => match std::fs::symlink_metadata(at) { - Ok(m) if m.file_type().is_symlink() => return Err(format!("automation path rejected: a link that leads nowhere: {path}")), + Ok(m) if m.file_type().is_symlink() => return Err(format!("automation path rejected: a link that leads nowhere: {shown}")), // There, yet its real path can't be had (no permission): nothing to compare. - Ok(_) => return Err(format!("automation path rejected: cannot resolve {path}: {e}")), + Ok(_) => return Err(format!("automation path rejected: cannot resolve {shown}: {e}")), Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => return Err(format!("automation path rejected: cannot resolve {path}: {e}")), + Err(e) => return Err(format!("automation path rejected: cannot resolve {shown}: {e}")), }, } let parent = at.parent(); @@ -189,46 +191,35 @@ fn resolve(path: &str) -> Result { at = parent; } (Some(Component::ParentDir), _) => { - return Err(format!("automation path rejected: parent traversal below a folder that doesn't exist: {path}")); + return Err(format!("automation path rejected: parent traversal below a folder that doesn't exist: {shown}")); } // Down to the root (or drive) and it doesn't exist either. _ => { let e = std::io::Error::from(std::io::ErrorKind::NotFound); - return Err(format!("automation path rejected: cannot resolve {path}: {e}")); + return Err(format!("automation path rejected: cannot resolve {shown}: {e}")); } } } } -/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on -/// Windows, whose file systems ignore it)? +/// Is `path` (resolved) `root` or inside it, component by component? fn inside(path: &Path, root: &Path) -> bool { let mut path = path.components(); - root.components().all(|r| path.next().is_some_and(|p| same_component(p, r))) + root.components().all(|r| path.next() == Some(r)) } /// Is `path` (resolved) exactly `root`, compared like [`inside`] does? fn same(path: &Path, root: &Path) -> bool { - path.components().count() == root.components().count() && path.components().zip(root.components()).all(|(p, r)| same_component(p, r)) + path.components().eq(root.components()) } -fn same_component(a: Component, b: Component) -> bool { - if a == b { - return true; - } - if !cfg!(windows) { - return false; - } - match (a.as_os_str().to_str(), b.as_os_str().to_str()) { - (Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(), - _ => false, - } -} - -/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file. +/// A Windows device name (`CON`, `NUL`, `COM1`, `LPT¹`… also with an extension or a `:`), which +/// names no file. fn is_device_name(component: &str) -> bool { - let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); - let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")); + let stem = component.split(['.', ':']).next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); + let numbered = |prefix: &str| { + stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³")) + }; matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT") } @@ -258,15 +249,15 @@ mod tests { #[test] fn paths_inside_the_roots_pass_and_others_dont() { let (base, roots) = folders("inside"); - assert_eq!(roots.check(&s(base.join("in/a.dxf")), Access::Read), Ok(())); - assert_eq!(roots.check(&s(base.join("in")), Access::Read), Ok(()), "the root itself"); - assert_eq!(roots.check(&s(base.join("in/sub/new.dxf")), Access::Read), Ok(()), "missing files are checked by their folder"); - assert_eq!(roots.check(&s(base.join("out/new/deeper/x.png")), Access::Write), Ok(()), "and by their nearest folder"); - let e = roots.check(&s(base.join("outside/secret.dxf")), Access::Read).unwrap_err(); + assert_eq!(roots.check(s(base.join("in/a.dxf")), Access::Read), Ok(())); + assert_eq!(roots.check(s(base.join("in")), Access::Read), Ok(()), "the root itself"); + assert_eq!(roots.check(s(base.join("in/sub/new.dxf")), Access::Read), Ok(()), "missing files are checked by their folder"); + assert_eq!(roots.check(s(base.join("out/new/deeper/x.png")), Access::Write), Ok(()), "and by their nearest folder"); + let e = roots.check(s(base.join("outside/secret.dxf")), Access::Read).unwrap_err(); assert!(e.starts_with("automation path rejected: outside the read root"), "{e}"); // Reads are allowed under the write root too; writes are not allowed under the read root. - assert_eq!(roots.check(&s(base.join("out/x.png")), Access::Read), Ok(()), "the write root also grants reads"); - let e = roots.check(&s(base.join("in/a.dxf")), Access::Write).unwrap_err(); + assert_eq!(roots.check(s(base.join("out/x.png")), Access::Read), Ok(()), "the write root also grants reads"); + let e = roots.check(s(base.join("in/a.dxf")), Access::Write).unwrap_err(); assert!(e.contains("outside the write root"), "{e}"); let _ = std::fs::remove_dir_all(base); } @@ -276,12 +267,12 @@ mod tests { fn reads_are_allowed_under_either_root() { let (base, _) = folders("either"); let write_only = AutomationRoots::new(None, Some(&base.join("out"))).unwrap().unwrap(); - assert_eq!(write_only.check(&s(base.join("out/new.dxf")), Access::Read), Ok(()), "a file to read back"); - let e = write_only.check(&s(base.join("in/a.dxf")), Access::Read).unwrap_err(); + assert_eq!(write_only.check(s(base.join("out/new.dxf")), Access::Read), Ok(()), "a file to read back"); + let e = write_only.check(s(base.join("in/a.dxf")), Access::Read).unwrap_err(); assert!(e.contains("outside the read root (or the write root)"), "{e}"); let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); - assert_eq!(read_only.check(&s(base.join("in/a.dxf")), Access::Read), Ok(())); - assert!(read_only.check(&s(base.join("out/new.dxf")), Access::Read).is_err(), "a read root alone grants no read of another folder"); + assert_eq!(read_only.check(s(base.join("in/a.dxf")), Access::Read), Ok(())); + assert!(read_only.check(s(base.join("out/new.dxf")), Access::Read).is_err(), "a read root alone grants no read of another folder"); let _ = std::fs::remove_dir_all(base); } @@ -296,7 +287,7 @@ mod tests { assert!(e.contains("the write root itself cannot be written"), "{p}: {e}"); } assert_eq!(roots.check(&out, Access::Read), Ok(()), "reading the root stays allowed"); - assert_eq!(roots.check(&s(base.join("out/new/x.png")), Access::Write), Ok(()), "a normal save inside still works"); + assert_eq!(roots.check(s(base.join("out/new/x.png")), Access::Write), Ok(()), "a normal save inside still works"); let _ = std::fs::remove_dir_all(base); } @@ -304,8 +295,8 @@ mod tests { fn a_sibling_with_the_same_prefix_is_outside() { let (base, roots) = folders("prefix"); std::fs::write(base.join("in2/b.dxf"), "0\nEOF\n").unwrap(); - assert!(roots.check(&s(base.join("in2/b.dxf")), Access::Read).is_err(), "in2 is not inside in"); - assert!(roots.check(&format!("{}2/c.dxf", s(base.join("in"))), Access::Read).is_err()); + assert!(roots.check(s(base.join("in2/b.dxf")), Access::Read).is_err(), "in2 is not inside in"); + assert!(roots.check(format!("{}2/c.dxf", s(base.join("in"))), Access::Read).is_err()); let _ = std::fs::remove_dir_all(base); } @@ -348,7 +339,7 @@ mod tests { assert!(AutomationRoots::new(None, None).unwrap().is_none()); // One root alone grants only its own access. let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); - let e = read_only.check(&s(base.join("in/x.dxf")), Access::Write).unwrap_err(); + let e = read_only.check(s(base.join("in/x.dxf")), Access::Write).unwrap_err(); assert!(e.contains("write authority is absent"), "{e}"); let _ = std::fs::remove_dir_all(base); } @@ -372,26 +363,106 @@ mod tests { let _ = std::fs::remove_dir_all(base); return; } - assert!(roots.check(&s(base.join("in/leak.dxf")), Access::Read).unwrap_err().contains("outside the read root"), "a file link out"); + assert!(roots.check(s(base.join("in/leak.dxf")), Access::Read).unwrap_err().contains("outside the read root"), "a file link out"); assert!(made(&base.join("outside"), &base.join("out/away"))); - let e = roots.check(&s(base.join("out/away/new.png")), Access::Write).unwrap_err(); + let e = roots.check(s(base.join("out/away/new.png")), Access::Write).unwrap_err(); assert!(e.contains("outside the write root"), "a folder link out: {e}"); assert!(made(&base.join("outside/gone.dxf"), &base.join("out/dangling.png"))); - let e = roots.check(&s(base.join("out/dangling.png")), Access::Write).unwrap_err(); + let e = roots.check(s(base.join("out/dangling.png")), Access::Write).unwrap_err(); assert!(e.contains("a link that leads nowhere"), "writing would create the file outside: {e}"); // A link to a folder inside the root stays inside. assert!(made(&base.join("in/sub"), &base.join("in/alias"))); - assert_eq!(roots.check(&s(base.join("in/alias/x.dxf")), Access::Read), Ok(())); + assert_eq!(roots.check(s(base.join("in/alias/x.dxf")), Access::Read), Ok(())); // A root given through a link is the folder it leads to. assert!(made(&base.join("in"), &base.join("in-link"))); let linked = AutomationRoots::new(Some(&base.join("in-link")), None).unwrap().unwrap(); - assert_eq!(linked.check(&s(base.join("in/a.dxf")), Access::Read), Ok(())); + assert_eq!(linked.check(s(base.join("in/a.dxf")), Access::Read), Ok(())); + let _ = std::fs::remove_dir_all(base); + } + + /// Names are compared exactly: `Root` isn't `root`, which a case-sensitive folder can hold beside it. + #[test] + fn a_name_differing_only_in_case_is_not_the_root() { + assert!(!inside(Path::new("/w/Root/x"), Path::new("/w/root"))); + assert!(!same(Path::new("/w/Root"), Path::new("/w/root"))); + assert!(inside(Path::new("/w/root/x"), Path::new("/w/root"))); + assert!(same(Path::new("/w/root"), Path::new("/w/root"))); + } + + #[test] + fn device_names_include_the_superscript_ports() { + for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.dxf", "NUL ", "COM¹", "lpt³.txt", "com²", "NUL:", "con:stream", "COM0", "lpt0.txt"] { + assert!(is_device_name(d), "{d}"); + } + for d in ["console.txt", "COM", "COM10", "LPT⁴", "a.nul", "nullable"] { + assert!(!is_device_name(d), "{d}"); + } + } + + /// A name that isn't text is checked as itself: the text of it names a file that isn't there, + /// which would pass, when the name itself is a link leading out. + #[cfg(unix)] + #[test] + fn a_name_that_is_not_text_is_judged_as_itself() { + use std::os::unix::ffi::OsStrExt; + let (base, roots) = folders("not-text"); + let name = std::ffi::OsStr::from_bytes(b"a\xff.dxf"); + let link = base.join("in").join(name); + // APFS and others refuse such a name: nothing to test there. + if std::os::unix::fs::symlink(base.join("outside/secret.dxf"), &link).is_err() { + eprintln!("skipped: this file system refuses a name that isn't text"); + let _ = std::fs::remove_dir_all(base); + return; + } + assert!(roots.check(&link, Access::Read).is_err()); + assert_eq!(roots.check(&*link.to_string_lossy(), Access::Read), Ok(()), "as text it is another file, which isn't there"); + let _ = std::fs::remove_dir_all(base); + } + + /// A name is judged by the folder it stands in as well as by where it leads. + #[cfg(unix)] + #[test] + fn a_link_standing_outside_the_write_root_is_refused() { + let (base, roots) = folders("entry"); + std::fs::write(base.join("out/t.dxf"), "x").unwrap(); + let link = base.join("outside/link.dxf"); + std::os::unix::fs::symlink(base.join("out/t.dxf"), &link).unwrap(); + assert!(roots.check(&link, Access::Write).unwrap_err().contains("stands outside the write root")); + assert_eq!(roots.check(&link, Access::Read), Ok(()), "reading it reads what is inside"); + let inner = base.join("out/link.dxf"); + std::os::unix::fs::symlink(base.join("out/t.dxf"), &inner).unwrap(); + assert_eq!(roots.check(&inner, Access::Write), Ok(())); + assert_eq!(roots.check(base.join("out/new/deep/x.dxf"), Access::Write), Ok(())); + let _ = std::fs::remove_dir_all(base); + } + + #[cfg(windows)] + #[test] + fn a_case_sensitive_windows_folder_can_hold_a_sibling_of_the_root() { + let base = std::env::temp_dir().join(format!("cc-file-access-sensitive-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let sensitive = std::process::Command::new("fsutil").args(["file", "setCaseSensitiveInfo"]).arg(&base).arg("enable").output(); + if !sensitive.is_ok_and(|o| o.status.success()) { + eprintln!("this runner can't make a case-sensitive folder: skipped"); + let _ = std::fs::remove_dir_all(&base); + return; + } + std::fs::create_dir(base.join("root")).unwrap(); + std::fs::create_dir(base.join("Root")).unwrap(); + std::fs::write(base.join("Root/secret.dxf"), "x").unwrap(); + let roots = AutomationRoots::new(Some(&base.join("root")), Some(&base.join("root"))).unwrap().unwrap(); + for p in ["Root/secret.dxf", "Root/new.dxf"] { + assert!(roots.check(&s(base.join(p)), Access::Read).is_err(), "{p}"); + assert!(roots.check(&s(base.join(p)), Access::Write).is_err(), "{p}"); + } + assert_eq!(roots.check(&s(base.join("root/new.dxf")), Access::Write), Ok(())); let _ = std::fs::remove_dir_all(base); } #[cfg(windows)] #[test] - fn windows_ignores_case_and_refuses_devices() { + fn windows_gives_a_root_its_real_spelling_and_refuses_devices() { let (base, roots) = folders("case"); let upper = s(base.join("IN/A.DXF")); assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}"); @@ -399,6 +470,7 @@ mod tests { let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err(); assert!(e.contains("reserved device names"), "{e}"); assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err()); + assert!(roots.check(&s(base.join("out/COM¹")), Access::Write).is_err()); assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(())); let _ = std::fs::remove_dir_all(base); } @@ -427,7 +499,7 @@ mod tests { for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL "] { assert!(is_device_name(d), "{d}"); } - for f in ["console", "com10", "COM0", "lpt", "a.svg", "nul-x"] { + for f in ["console", "com10", "lpt", "a.svg", "nul-x"] { assert!(!is_device_name(f), "{f}"); } } diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index f2b673a826..322317e094 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -90,6 +90,8 @@ pub const NO_FILES: &[&str] = &[ "isolateobjects", "hideobjects", "unisolateobjects", + "xclip", + "xclipframe", "zoom", "zoom.realtime", "zoom.dynamic", diff --git a/crates/engine/src/lisp/builtins/files.rs b/crates/engine/src/lisp/builtins/files.rs index 1f19c71aff..58cb1fb3a5 100644 --- a/crates/engine/src/lisp/builtins/files.rs +++ b/crates/engine/src/lisp/builtins/files.rs @@ -77,7 +77,7 @@ pub fn read_text_file(path: impl AsRef) -> Option { // Read through a byte-limited, regular-file-only reader so a path naming an endless device // cannot exhaust memory before the 64 MiB cap is enforced (CWE-400). const MAX: usize = 64 * 1024 * 1024; - crate::file_access::check_read(&path.as_ref().to_string_lossy()).ok()?; + crate::file_access::check_read(path.as_ref()).ok()?; let bytes = crate::capped_read::read_capped(path.as_ref(), MAX).ok()?; Some(String::from_utf8_lossy(&bytes).into_owned()) } diff --git a/crates/engine/tests/dash_wblock.rs b/crates/engine/tests/dash_wblock.rs index 52d456f423..d29cdb5cc4 100644 --- a/crates/engine/tests/dash_wblock.rs +++ b/crates/engine/tests/dash_wblock.rs @@ -301,3 +301,22 @@ fn a_dash_wblock_refused_during_refedit_leaves_oops_as_it_was() { s.execute("oops", &json!({})).unwrap(); assert!(alive(&s, c)); } + +/// Outside the automation roots the prompt doesn't say whether a file is there. +#[test] +fn the_replace_prompt_says_nothing_about_a_file_outside_the_roots() { + let (mut s, ..) = drawing(); + let dir = TempDir::new("dash-wblock-roots"); + for d in ["in", "out", "outside"] { + std::fs::create_dir(dir.join(d)).unwrap(); + } + let there = dir.join("outside/there.dwg"); + std::fs::write(&there, "old").unwrap(); + let write = dir.join("out"); + let roots = cadcraft_engine::file_access::AutomationRoots::new(Some(&dir.join("in")), Some(&write)).unwrap(); + cadcraft_engine::file_access::confine(roots.as_ref(), || { + s.cmdline("-wblock").unwrap(); + s.cmdline(&there.display().to_string()).unwrap(); + assert!(!s.prompt_text().contains("already exists"), "{}", s.prompt_text()); + }); +} diff --git a/docs/mcp.md b/docs/mcp.md index 9c26915049..709f8ddd85 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -58,9 +58,12 @@ configuration works across the suite) keep the agent to the folders you give it: file or folder link that leads out of a root is outside it. For a file that doesn't exist yet, its nearest existing folder's links are followed and the rest must be plain names, so `..` below a folder that doesn't exist is refused, as is a link that leads nowhere. The result is compared - with the root by whole folder names: `/work2/x` is not inside `/work`. On Windows case is ignored, - UNC paths are resolved like drive-letter ones, and device names (`CON`, `NUL`, `COM1`…) are - refused. + with the root by whole folder names, exactly: `/work2/x` is not inside `/work`, and on Windows + a folder's own case comes from the file system, so a case-sensitive folder's `Root` is not + `root`. On Windows UNC paths are resolved like drive-letter ones, and device names (`CON`, `NUL`, + `COM1`, `LPT¹`…) are refused. +- A path you write must also stand under the write root: a link outside it pointing in is refused, + because a drawing's `.bak` goes beside the link and a delete removes the link. - A refused path is an ordinary tool error with `isError: true` that the agent can read and correct, for example `automation path rejected: outside the write root /work/project/out: /etc/x.png`, `automation path rejected: outside the read root (or the write @@ -72,6 +75,8 @@ configuration works across the suite) keep the agent to the folders you give it: - A command runs under the roots only if it is classified (`crates/engine/src/file_access/commands.rs`): one nobody classified is refused, whatever it does. `drawingrecovery` is refused, and SAVEFILEPATH can't be changed, because both work on the server's autosave folder. +- SHX fonts beside an opened drawing aren't searched under the roots, since one could be a link + leading out. Set `CADCRAFT_SHXPATH` for the server to supply fonts. - The server itself still reads the system's fonts, from the system font folders and `CADCRAFT_SHXPATH`. Their paths come from the server's setup, never from the agent, but a font file named by a drawing can decide which of them is read. From 290e578c2f5311d4c81c02733cdac124c9c1de1e Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Fri, 6 Nov 2026 10:01:43 +0530 Subject: [PATCH 05/27] Give the automation root tests folders of their own, and a control for the Replace prompt The fixtures took a predictable name in the shared temp folder and removed whatever was there. They now create the folder exclusively. The -WBLOCK test also shows the prompt appearing without roots, so its absence under them is the check and not a change in the flow. --- apps/cadcraft-cli/tests/mcp_roots.rs | 16 ++++++++++++++-- apps/cadcraft-cli/tests/mcp_roots_walk.rs | 18 +++++++++++++++--- crates/engine/src/file_access.rs | 20 +++++++++++++++----- crates/engine/tests/dash_wblock.rs | 5 +++++ 4 files changed, 49 insertions(+), 10 deletions(-) diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs index 71e38adc04..936cf727a1 100644 --- a/apps/cadcraft-cli/tests/mcp_roots.rs +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -13,11 +13,23 @@ use serde_json::{Value, json}; const INIT: &str = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#; +/// A new folder of this test's own: made here, so nothing else put it there first. +fn fresh_dir(tag: &str) -> PathBuf { + let mut n = 0u32; + loop { + let dir = std::env::temp_dir().join(format!("cc-mcp-roots-{tag}-{}-{n}", std::process::id())); + match std::fs::create_dir(&dir) { + Ok(()) => return dir, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, + Err(e) => panic!("{}: {e}", dir.display()), + } + } +} + /// A folder holding `in` (the read root, with `a.dxf`), `out` (the write root), `outside` (with /// `b.dxf`) and `in2` (a sibling with the same prefix as `in`). fn folders(tag: &str) -> PathBuf { - let base = std::env::temp_dir().join(format!("cc-mcp-roots-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&base); + let base = fresh_dir(tag); for d in ["in", "out", "outside", "in2"] { std::fs::create_dir_all(base.join(d)).unwrap(); } diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index 784e5b005c..5242124d8b 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -103,6 +103,19 @@ impl Drop for Server { } /// The folders of one walk: `in` and `out` are the roots, nothing under `outside` may be touched. +/// A new folder of this test's own: made here, so nothing else put it there first. +fn fresh_dir(tag: &str) -> PathBuf { + let mut n = 0u32; + loop { + let dir = std::env::temp_dir().join(format!("cc-walk-{tag}-{}-{n}", std::process::id())); + match std::fs::create_dir(&dir) { + Ok(()) => return dir, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, + Err(e) => panic!("{}: {e}", dir.display()), + } + } +} + struct Fixture { base: PathBuf, outside: PathBuf, @@ -114,10 +127,9 @@ struct Fixture { impl Fixture { fn new(tag: &str) -> Self { - let base = std::env::temp_dir().join(format!("cc-walk-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&base); + let base = fresh_dir(tag); for d in ["in", "out"] { - std::fs::create_dir_all(base.join(d)).unwrap(); + std::fs::create_dir(base.join(d)).unwrap(); } let probe = base.join("probe"); std::fs::write(&probe, "x").unwrap(); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 7e5bc285a5..bc376913ec 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -227,10 +227,22 @@ fn is_device_name(component: &str) -> bool { mod tests { use super::*; + /// A new folder of this test's own: made here, so nothing else put it there first. + fn fresh_dir(tag: &str) -> PathBuf { + let mut n = 0u32; + loop { + let dir = std::env::temp_dir().join(format!("cc-file-access-{tag}-{}-{n}", std::process::id())); + match std::fs::create_dir(&dir) { + Ok(()) => return dir, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, + Err(e) => panic!("{}: {e}", dir.display()), + } + } + } + /// A fresh folder holding `in` (read root), `out` (write root) and `outside`. fn folders(name: &str) -> (PathBuf, Arc) { - let base = std::env::temp_dir().join(format!("cc-file-access-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&base); + let base = fresh_dir(name); for d in ["in/sub", "out", "outside", "in2"] { std::fs::create_dir_all(base.join(d)).unwrap(); } @@ -439,9 +451,7 @@ mod tests { #[cfg(windows)] #[test] fn a_case_sensitive_windows_folder_can_hold_a_sibling_of_the_root() { - let base = std::env::temp_dir().join(format!("cc-file-access-sensitive-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&base); - std::fs::create_dir_all(&base).unwrap(); + let base = fresh_dir("sensitive"); let sensitive = std::process::Command::new("fsutil").args(["file", "setCaseSensitiveInfo"]).arg(&base).arg("enable").output(); if !sensitive.is_ok_and(|o| o.status.success()) { eprintln!("this runner can't make a case-sensitive folder: skipped"); diff --git a/crates/engine/tests/dash_wblock.rs b/crates/engine/tests/dash_wblock.rs index d29cdb5cc4..b4c2f7f670 100644 --- a/crates/engine/tests/dash_wblock.rs +++ b/crates/engine/tests/dash_wblock.rs @@ -312,6 +312,11 @@ fn the_replace_prompt_says_nothing_about_a_file_outside_the_roots() { } let there = dir.join("outside/there.dwg"); std::fs::write(&there, "old").unwrap(); + // Without roots the same file gets the prompt, so its absence below is the check's doing. + let (mut free, ..) = drawing(); + free.cmdline("-wblock").unwrap(); + free.cmdline(&there.display().to_string()).unwrap(); + assert!(free.prompt_text().contains("already exists"), "{}", free.prompt_text()); let write = dir.join("out"); let roots = cadcraft_engine::file_access::AutomationRoots::new(Some(&dir.join("in")), Some(&write)).unwrap(); cadcraft_engine::file_access::confine(roots.as_ref(), || { From b19c3665d93d77fa2a6b8c405a086b95ca2df53c Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:09:49 +0530 Subject: [PATCH 06/27] Classify the commands main added under the automation roots `breakatpoint`, `chprop` and `properties.set` change objects in the drawing and touch no file. --- crates/engine/src/file_access/commands.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index 322317e094..d33a9a3557 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -470,6 +470,9 @@ pub const NO_FILES: &[&str] = &[ "constraintinfer", "constraints.inspect", "constraints.dof", + "breakatpoint", + "chprop", + "properties.set", ]; /// Why command `id` may not run here; `None` when it may. Without roots in force everything may. From 8314fb87ef224b637e9fcb705fe2d57dfc169073 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:40:07 +0530 Subject: [PATCH 07/27] Search fonts beside a drawing when they stay inside the roots, and keep the walk honest Under the roots the folder was skipped outright, so a drawing lost its own SHX fonts. It is now skipped only if a font there leads out. The fixture deleted the running server's working directory on reset, so a relative path met a missing folder and not the roots. Test folders now clean up when a test fails. Three NO_FILES entries I added on the last merge were duplicates: those commands already had a row. --- apps/cadcraft-cli/tests/mcp_roots.rs | 32 +++++++----- apps/cadcraft-cli/tests/mcp_roots_walk.rs | 60 ++++++++++++++++++++++- crates/engine/src/cmd/file.rs | 20 ++++++-- crates/engine/src/file_access.rs | 42 ++++++++-------- crates/engine/src/file_access/commands.rs | 3 -- docs/mcp.md | 4 +- 6 files changed, 118 insertions(+), 43 deletions(-) diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs index 936cf727a1..99ecb0ec12 100644 --- a/apps/cadcraft-cli/tests/mcp_roots.rs +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -13,13 +13,29 @@ use serde_json::{Value, json}; const INIT: &str = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#; +/// A folder of a test's own, removed when the test ends, also when it fails. +struct TestDir(PathBuf); + +impl std::ops::Deref for TestDir { + type Target = Path; + fn deref(&self) -> &Path { + &self.0 + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + /// A new folder of this test's own: made here, so nothing else put it there first. -fn fresh_dir(tag: &str) -> PathBuf { +fn fresh_dir(tag: &str) -> TestDir { let mut n = 0u32; loop { let dir = std::env::temp_dir().join(format!("cc-mcp-roots-{tag}-{}-{n}", std::process::id())); match std::fs::create_dir(&dir) { - Ok(()) => return dir, + Ok(()) => return TestDir(dir), Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, Err(e) => panic!("{}: {e}", dir.display()), } @@ -28,7 +44,7 @@ fn fresh_dir(tag: &str) -> PathBuf { /// A folder holding `in` (the read root, with `a.dxf`), `out` (the write root), `outside` (with /// `b.dxf`) and `in2` (a sibling with the same prefix as `in`). -fn folders(tag: &str) -> PathBuf { +fn folders(tag: &str) -> TestDir { let base = fresh_dir(tag); for d in ["in", "out", "outside", "in2"] { std::fs::create_dir_all(base.join(d)).unwrap(); @@ -119,7 +135,6 @@ fn files_open_only_from_inside_the_read_root() { refused(&t[3], "outside the read root"); // A refused path is an ordinary tool error; the session keeps working. ok(&t[4]); - let _ = std::fs::remove_dir_all(base); } /// Writes stay inside the write root, the root itself is refused, and no temporary file is left outside. @@ -172,9 +187,8 @@ fn writes_go_only_into_the_write_root_and_leave_no_temp_file_outside() { std::fs::read_dir(base.join("outside")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); assert_eq!(leftovers, ["b.dxf"], "nothing was written outside the roots"); let temps: Vec = - std::fs::read_dir(&base).unwrap().filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| n.ends_with(".cadcraft-tmp")).collect(); + std::fs::read_dir(&*base).unwrap().filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| n.ends_with(".cadcraft-tmp")).collect(); assert!(temps.is_empty(), "no temporary file beside or outside the roots: {temps:?}"); - let _ = std::fs::remove_dir_all(base); } /// A root left out grants none of its own access: a read root allows no writes, while a write root also allows reads. @@ -205,7 +219,6 @@ fn a_root_left_out_grants_none_of_its_access() { ok(&t[1]); assert!(base.join("out/new.dxf").is_file()); ok(&t[2]); - let _ = std::fs::remove_dir_all(base); } /// The shared plotter settings folder is outside the roots: every action refuses and it is unchanged. @@ -250,7 +263,6 @@ fn plotter_settings_outside_the_roots_are_refused() { let names: Vec = std::fs::read_dir(&settings).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); assert_eq!(names, ["Office.plotter.json"], "nothing was created or deleted in the settings folder"); assert!(!settings.join("Office.plotter.json.cadcraft-tmp").exists()); - let _ = std::fs::remove_dir_all(base); } #[test] @@ -262,7 +274,6 @@ fn without_roots_files_are_reachable_as_before() { ok(&t[0]); ok(&t[1]); assert!(base.join("outside/new.dxf").is_file()); - let _ = std::fs::remove_dir_all(base); } #[cfg(unix)] @@ -279,7 +290,6 @@ fn links_out_of_a_root_are_refused() { refused(&t[0], "outside the read root"); refused(&t[1], "outside the write root"); assert!(!base.join("outside/new.dxf").exists()); - let _ = std::fs::remove_dir_all(base); } #[test] @@ -323,7 +333,6 @@ fn every_file_a_command_touches_is_held_to_the_roots() { assert!(base.join("out/plot.pdf").is_file()); refused(&t[10], "outside the write root"); assert!(!base.join("outside/plot.pdf").exists()); - let _ = std::fs::remove_dir_all(base); } #[test] @@ -355,5 +364,4 @@ fn missing_roots_and_roots_with_connect_fail_at_startup() { let out = start(&["--connect", "127.0.0.1:1", "--automation-read-root", &s(&base.join("in"))]); assert!(!out.status.success() && out.stdout.is_empty()); assert!(String::from_utf8_lossy(&out.stderr).contains("headless MCP server")); - let _ = std::fs::remove_dir_all(base); } diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index 5242124d8b..11492660da 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -116,6 +116,18 @@ fn fresh_dir(tag: &str) -> PathBuf { } } +/// Remove the file or folder at `p`. +fn remove(p: &Path) { + let _ = if p.is_dir() { std::fs::remove_dir_all(p) } else { std::fs::remove_file(p) }; +} + +/// Remove what `dir` holds, if it exists. +fn clear(dir: &Path) { + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + remove(&entry.path()); + } +} + struct Fixture { base: PathBuf, outside: PathBuf, @@ -146,7 +158,13 @@ impl Fixture { /// Lay out `outside` afresh and start watching it. fn reset(&mut self) { let o = self.outside.clone(); - let _ = std::fs::remove_dir_all(&o); + // The running server's working directory stays: without it a relative path can't be resolved. + clear(&o.join("cwd")); + for entry in std::fs::read_dir(&o).into_iter().flatten().flatten() { + if entry.file_name() != "cwd" { + remove(&entry.path()); + } + } for d in ["cwd", "config/plotters", "recover"] { std::fs::create_dir_all(o.join(d)).unwrap(); } @@ -621,3 +639,43 @@ fn without_roots_an_unreadable_settings_folder_still_lists_devices() { let list = server.execute("plottermanager", json!({"action": "list"})).unwrap(); assert!(list.contains("devices"), "{list}"); } + +/// A font beside a drawing inside the roots is still used. +#[test] +fn a_font_beside_a_drawing_inside_the_roots_is_used() { + let f = Fixture::new("font-inside"); + let host = f.base.join("in/host.dxf"); + { + let mut free = Server::start(&[], &f.outside.join("cwd"), &f.outside.join("config")); + free.execute("new", json!({})).unwrap(); + free.execute("style", json!({"name": "Walk", "font": "walkinside.shx"})).unwrap(); + free.execute("style.current", json!({"name": "Walk"})).unwrap(); + free.execute("text", json!({"at": [0, 0], "height": 5, "text": "walk"})).unwrap(); + free.execute("saveas", json!({"path": s(&host)})).unwrap(); + } + let font = f.base.join("in/walkinside.shx"); + std::fs::write(&font, b"AutoCAD-86 shapes 1.0").unwrap(); + age_access_time(&font); + let before = std::fs::metadata(&font).unwrap().accessed().unwrap(); + let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))]; + let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config")); + server.tool("open", json!({"path": s(&host)})).unwrap(); + server.tool("render", json!({})).unwrap(); + if f.sees_reads { + assert_ne!(std::fs::metadata(&font).unwrap().accessed().unwrap(), before, "the font was read"); + } +} + +/// The fixture leaves the server's working directory in place, so a relative path meets the roots +/// and not a folder that has gone. +#[test] +fn a_relative_path_is_refused_by_the_roots() { + let mut f = Fixture::new("relative"); + let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))]; + let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config")); + f.reset(); + let reply = server.tool("open", json!({"path": "../canary.dxf"})).unwrap(); + assert!(reply.contains("outside the read root"), "{reply}"); + let touched = f.touched(); + assert!(touched.is_empty(), "{touched:?}"); +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 435cfd2cf0..0d17665cc5 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -337,16 +337,28 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result bool { + crate::file_access::current().is_none() + || std::fs::read_dir(dir).is_ok_and(|entries| { + entries + .flatten() + .all(|e| !e.file_name().to_string_lossy().to_ascii_lowercase().ends_with(".shx") || crate::file_access::check_read(e.path()).is_ok()) + }) +} + fn add_read(s: &mut Session, drawing: Drawing, binary_dxf: bool, name: &str, path: Option) -> usize { let notes = drawing.read_notes.clone(); let i = s.open_drawing(drawing, &file_name(name), path); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index bc376913ec..ccaa241058 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -227,13 +227,29 @@ fn is_device_name(component: &str) -> bool { mod tests { use super::*; + /// A folder of a test's own, removed when the test ends, also when it fails. + struct TestDir(PathBuf); + + impl std::ops::Deref for TestDir { + type Target = Path; + fn deref(&self) -> &Path { + &self.0 + } + } + + impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + /// A new folder of this test's own: made here, so nothing else put it there first. - fn fresh_dir(tag: &str) -> PathBuf { + fn fresh_dir(tag: &str) -> TestDir { let mut n = 0u32; loop { let dir = std::env::temp_dir().join(format!("cc-file-access-{tag}-{}-{n}", std::process::id())); match std::fs::create_dir(&dir) { - Ok(()) => return dir, + Ok(()) => return TestDir(dir), Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, Err(e) => panic!("{}: {e}", dir.display()), } @@ -241,7 +257,7 @@ mod tests { } /// A fresh folder holding `in` (read root), `out` (write root) and `outside`. - fn folders(name: &str) -> (PathBuf, Arc) { + fn folders(name: &str) -> (TestDir, Arc) { let base = fresh_dir(name); for d in ["in/sub", "out", "outside", "in2"] { std::fs::create_dir_all(base.join(d)).unwrap(); @@ -271,7 +287,6 @@ mod tests { assert_eq!(roots.check(s(base.join("out/x.png")), Access::Read), Ok(()), "the write root also grants reads"); let e = roots.check(s(base.join("in/a.dxf")), Access::Write).unwrap_err(); assert!(e.contains("outside the write root"), "{e}"); - let _ = std::fs::remove_dir_all(base); } /// A write-only root still permits reads inside it; reads outside both roots are refused. @@ -285,7 +300,6 @@ mod tests { let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); assert_eq!(read_only.check(s(base.join("in/a.dxf")), Access::Read), Ok(())); assert!(read_only.check(s(base.join("out/new.dxf")), Access::Read).is_err(), "a read root alone grants no read of another folder"); - let _ = std::fs::remove_dir_all(base); } /// A write to the write root itself would put its `.cadcraft-tmp` file beside the root: refused. @@ -300,7 +314,6 @@ mod tests { } assert_eq!(roots.check(&out, Access::Read), Ok(()), "reading the root stays allowed"); assert_eq!(roots.check(s(base.join("out/new/x.png")), Access::Write), Ok(()), "a normal save inside still works"); - let _ = std::fs::remove_dir_all(base); } #[test] @@ -309,7 +322,6 @@ mod tests { std::fs::write(base.join("in2/b.dxf"), "0\nEOF\n").unwrap(); assert!(roots.check(s(base.join("in2/b.dxf")), Access::Read).is_err(), "in2 is not inside in"); assert!(roots.check(format!("{}2/c.dxf", s(base.join("in"))), Access::Read).is_err()); - let _ = std::fs::remove_dir_all(base); } #[test] @@ -324,16 +336,14 @@ mod tests { let e = roots.check(&missing, Access::Write).unwrap_err(); // Windows resolves `..` by name first (so does opening the file there): then it's outside. assert!(e.contains("parent traversal below a folder that doesn't exist") || e.contains("outside the write root"), "{e}"); - let _ = std::fs::remove_dir_all(base); } #[test] fn relative_paths_resolve_against_the_working_directory() { - let (base, roots) = folders("relative"); + let (_base, roots) = folders("relative"); // The tests' working directory is the crate's folder: not inside the roots. assert!(roots.check("a.dxf", Access::Read).unwrap_err().contains("outside the read root")); assert!(roots.check("", Access::Read).unwrap_err().contains("path is empty")); - let _ = std::fs::remove_dir_all(base); } #[test] @@ -353,7 +363,6 @@ mod tests { let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); let e = read_only.check(s(base.join("in/x.dxf")), Access::Write).unwrap_err(); assert!(e.contains("write authority is absent"), "{e}"); - let _ = std::fs::remove_dir_all(base); } #[test] @@ -372,7 +381,6 @@ mod tests { // Windows needs Developer Mode or elevation to make links: nothing to test without them. if !made(&base.join("outside/secret.dxf"), &base.join("in/leak.dxf")) { eprintln!("skipped: symbolic links can't be made here"); - let _ = std::fs::remove_dir_all(base); return; } assert!(roots.check(s(base.join("in/leak.dxf")), Access::Read).unwrap_err().contains("outside the read root"), "a file link out"); @@ -389,7 +397,6 @@ mod tests { assert!(made(&base.join("in"), &base.join("in-link"))); let linked = AutomationRoots::new(Some(&base.join("in-link")), None).unwrap().unwrap(); assert_eq!(linked.check(s(base.join("in/a.dxf")), Access::Read), Ok(())); - let _ = std::fs::remove_dir_all(base); } /// Names are compared exactly: `Root` isn't `root`, which a case-sensitive folder can hold beside it. @@ -423,12 +430,10 @@ mod tests { // APFS and others refuse such a name: nothing to test there. if std::os::unix::fs::symlink(base.join("outside/secret.dxf"), &link).is_err() { eprintln!("skipped: this file system refuses a name that isn't text"); - let _ = std::fs::remove_dir_all(base); return; } assert!(roots.check(&link, Access::Read).is_err()); assert_eq!(roots.check(&*link.to_string_lossy(), Access::Read), Ok(()), "as text it is another file, which isn't there"); - let _ = std::fs::remove_dir_all(base); } /// A name is judged by the folder it stands in as well as by where it leads. @@ -445,17 +450,15 @@ mod tests { std::os::unix::fs::symlink(base.join("out/t.dxf"), &inner).unwrap(); assert_eq!(roots.check(&inner, Access::Write), Ok(())); assert_eq!(roots.check(base.join("out/new/deep/x.dxf"), Access::Write), Ok(())); - let _ = std::fs::remove_dir_all(base); } #[cfg(windows)] #[test] fn a_case_sensitive_windows_folder_can_hold_a_sibling_of_the_root() { let base = fresh_dir("sensitive"); - let sensitive = std::process::Command::new("fsutil").args(["file", "setCaseSensitiveInfo"]).arg(&base).arg("enable").output(); + let sensitive = std::process::Command::new("fsutil").args(["file", "setCaseSensitiveInfo"]).arg(&*base).arg("enable").output(); if !sensitive.is_ok_and(|o| o.status.success()) { eprintln!("this runner can't make a case-sensitive folder: skipped"); - let _ = std::fs::remove_dir_all(&base); return; } std::fs::create_dir(base.join("root")).unwrap(); @@ -467,7 +470,6 @@ mod tests { assert!(roots.check(&s(base.join(p)), Access::Write).is_err(), "{p}"); } assert_eq!(roots.check(&s(base.join("root/new.dxf")), Access::Write), Ok(())); - let _ = std::fs::remove_dir_all(base); } #[cfg(windows)] @@ -482,7 +484,6 @@ mod tests { assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err()); assert!(roots.check(&s(base.join("out/COM¹")), Access::Write).is_err()); assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(())); - let _ = std::fs::remove_dir_all(base); } #[test] @@ -501,7 +502,6 @@ mod tests { assert!(r.is_err()); assert_eq!(check_read(&outside), Ok(()), "restored after a panic"); assert_eq!(confine(None, || check_read(&outside)), Ok(())); - let _ = std::fs::remove_dir_all(base); } #[test] diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index d33a9a3557..322317e094 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -470,9 +470,6 @@ pub const NO_FILES: &[&str] = &[ "constraintinfer", "constraints.inspect", "constraints.dof", - "breakatpoint", - "chprop", - "properties.set", ]; /// Why command `id` may not run here; `None` when it may. Without roots in force everything may. diff --git a/docs/mcp.md b/docs/mcp.md index 709f8ddd85..d12a77988d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -75,8 +75,8 @@ configuration works across the suite) keep the agent to the folders you give it: - A command runs under the roots only if it is classified (`crates/engine/src/file_access/commands.rs`): one nobody classified is refused, whatever it does. `drawingrecovery` is refused, and SAVEFILEPATH can't be changed, because both work on the server's autosave folder. -- SHX fonts beside an opened drawing aren't searched under the roots, since one could be a link - leading out. Set `CADCRAFT_SHXPATH` for the server to supply fonts. +- SHX fonts beside an opened drawing are searched only if every `.shx` in that folder stays inside + the roots: one link leading out and the folder is skipped. - The server itself still reads the system's fonts, from the system font folders and `CADCRAFT_SHXPATH`. Their paths come from the server's setup, never from the agent, but a font file named by a drawing can decide which of them is read. From 1a64ca23f586fc169fced0f8cf46754e6f7ab77d Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:08:28 +0530 Subject: [PATCH 08/27] Document the functions the automation roots touch CodeRabbit measures docstring coverage over the functions a PR touches, and this one was at 62%, under the repository's 80% threshold. --- apps/cadcraft-cli/src/args.rs | 3 +++ apps/cadcraft-cli/src/mcp.rs | 1 + apps/cadcraft-cli/tests/mcp_roots.rs | 8 ++++++++ apps/cadcraft-cli/tests/mcp_roots_walk.rs | 7 +++++++ crates/engine/src/cmd/audit.rs | 2 ++ crates/engine/src/cmd/blocks/extract.rs | 1 + crates/engine/src/cmd/blocks/insert_file.rs | 1 + crates/engine/src/cmd/blocks/xref.rs | 1 + crates/engine/src/cmd/blocks/xref/load.rs | 1 + crates/engine/src/cmd/exchange.rs | 1 + crates/engine/src/cmd/file.rs | 1 + crates/engine/src/cmd/file/compare.rs | 1 + crates/engine/src/cmd/file/template.rs | 1 + crates/engine/src/cmd/helpers.rs | 1 + crates/engine/src/cmd/layout/plotstyle.rs | 1 + crates/engine/src/cmd/plotters.rs | 1 + crates/engine/src/file_access.rs | 10 ++++++++++ crates/engine/src/file_access/commands.rs | 1 + crates/engine/src/lisp/builtins/files.rs | 3 +++ crates/engine/src/session/execute.rs | 1 + crates/engine/src/sysvars.rs | 1 + crates/engine/tests/dash_wblock.rs | 1 + crates/mcp/src/backend.rs | 3 +++ 23 files changed, 52 insertions(+) diff --git a/apps/cadcraft-cli/src/args.rs b/apps/cadcraft-cli/src/args.rs index 5d3864e0e7..c8daf8d149 100644 --- a/apps/cadcraft-cli/src/args.rs +++ b/apps/cadcraft-cli/src/args.rs @@ -423,6 +423,7 @@ enum UsageError { } impl UsageError { + /// This error in clap's form, so it prints with the usual usage text. fn into_clap(self, cmd: &mut clap::Command) -> clap::Error { let kind = match self { Self::FramingNeedsImage { .. } | Self::OutIsInput(_) | Self::AutomationRootsNeedHeadless => ErrorKind::ArgumentConflict, @@ -530,6 +531,7 @@ pub(crate) enum McpTarget { } impl McpArgs { + /// What these arguments ask the server to talk to. pub(crate) fn target(&self) -> McpTarget { match &self.connect { // `--launch` connects at the first call too (the app opens then). @@ -663,6 +665,7 @@ mod tests { } } + /// Without `--connect` the server runs headless, confining nothing unless asked. #[test] fn mcp_without_connect_is_headless() { assert_eq!(mcp(&[]).unwrap(), McpTarget::Headless { read_root: None, write_root: None }); diff --git a/apps/cadcraft-cli/src/mcp.rs b/apps/cadcraft-cli/src/mcp.rs index 4727d29c16..ea6849f71c 100644 --- a/apps/cadcraft-cli/src/mcp.rs +++ b/apps/cadcraft-cli/src/mcp.rs @@ -1,6 +1,7 @@ use super::args::{McpArgs, McpTarget}; use super::error::{CliError, Result}; +/// Serve MCP on stdin and stdout against the running app or a headless session held to any roots given. pub(crate) fn mcp(a: &McpArgs) -> Result { let backend: Box = match a.target() { McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)), diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs index 99ecb0ec12..6011842b9f 100644 --- a/apps/cadcraft-cli/tests/mcp_roots.rs +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -56,6 +56,7 @@ fn folders(tag: &str) -> TestDir { base } +/// `p` as the text a tool call passes. fn s(p: &Path) -> String { p.to_string_lossy().into_owned() } @@ -106,15 +107,18 @@ fn run_env(args: &[&str], calls: &[(&str, Value)], env: &[(&str, &str)]) -> (Out (out, tools) } +/// The call succeeded. fn ok(t: &Tool) { assert!(!t.error, "should be allowed: {}", t.text); } +/// The call was refused, saying `why`. fn refused(t: &Tool, why: &str) { assert!(t.error, "should be refused ({why}): {}", t.text); assert!(t.text.contains(why), "should say `{why}`: {}", t.text); } +/// `open` and every other read stay inside the read root or the write root. #[test] fn files_open_only_from_inside_the_read_root() { let base = folders("open"); @@ -265,6 +269,7 @@ fn plotter_settings_outside_the_roots_are_refused() { assert!(!settings.join("Office.plotter.json.cadcraft-tmp").exists()); } +/// With no roots nothing changes: files anywhere can be reached. #[test] fn without_roots_files_are_reachable_as_before() { let base = folders("none"); @@ -276,6 +281,7 @@ fn without_roots_files_are_reachable_as_before() { assert!(base.join("outside/new.dxf").is_file()); } +/// A link inside a root leading out is refused for reads and writes. #[cfg(unix)] #[test] fn links_out_of_a_root_are_refused() { @@ -292,6 +298,7 @@ fn links_out_of_a_root_are_refused() { assert!(!base.join("outside/new.dxf").exists()); } +/// Each kind of command that touches a file is refused outside the roots. #[test] fn every_file_a_command_touches_is_held_to_the_roots() { let base = folders("commands"); @@ -335,6 +342,7 @@ fn every_file_a_command_touches_is_held_to_the_roots() { assert!(!base.join("outside/plot.pdf").exists()); } +/// A root that can't be opened, or roots with `--connect`, stop the server at startup. #[test] fn missing_roots_and_roots_with_connect_fail_at_startup() { let base = folders("bad-roots"); diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index 11492660da..d74c71631a 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -30,6 +30,7 @@ const PNG: &[u8] = &[ 0xAE, 0x42, 0x60, 0x82, ]; +/// `p` as the text a tool call passes. fn s(p: &Path) -> String { p.to_string_lossy().into_owned() } @@ -43,6 +44,7 @@ struct Server { } impl Server { + /// Start the real binary as an MCP server and initialize it. fn start(args: &[String], cwd: &Path, config: &Path) -> Self { let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) .arg("mcp") @@ -71,6 +73,7 @@ impl Server { server } + /// Send one JSON-RPC request; `None` if the server stopped answering. fn request(&mut self, method: &str, params: Value) -> Option { let id = self.next; self.next += 1; @@ -90,6 +93,7 @@ impl Server { Some(reply["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string()) } + /// Run an engine command through the `execute` tool. fn execute(&mut self, command: &str, params: Value) -> Option { self.tool("execute", json!({"command": command, "params": params})) } @@ -138,6 +142,7 @@ struct Fixture { } impl Fixture { + /// A new fixture, finding out whether this file system records reads. fn new(tag: &str) -> Self { let base = fresh_dir(tag); for d in ["in", "out"] { @@ -224,6 +229,7 @@ impl Drop for Fixture { } } +/// Every file and folder under `dir`. fn tree(dir: &Path) -> Vec { let mut out = vec![dir.to_path_buf()]; for e in std::fs::read_dir(dir).unwrap().flatten() { @@ -458,6 +464,7 @@ fn walk(tag: &str, roots: bool) -> Walk { result } +/// One line saying what a walk saw. fn summary(w: &Walk) -> String { format!( "{} commands, {} calls, reads seen: {}, {} commands touched files outside, {} calls lost the server", diff --git a/crates/engine/src/cmd/audit.rs b/crates/engine/src/cmd/audit.rs index 8167695986..7ede5a67cd 100644 --- a/crates/engine/src/cmd/audit.rs +++ b/crates/engine/src/cmd/audit.rs @@ -134,6 +134,7 @@ fn run_recover(s: &mut Session, p: &Value) -> Result { Ok(r) } +/// Write the report to the `.adt` file beside the saved drawing, held to the automation roots. #[cfg(not(target_arch = "wasm32"))] fn write_audit_log(s: &Session, report: &crate::audit::Report) { let (path_str, title) = match s.state() { @@ -165,6 +166,7 @@ fn read_path(cmd: &str, path: &str) -> Result> { std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}"))) } +/// The bytes of the drawing at `path`, held to the automation roots. #[cfg(target_arch = "wasm32")] fn read_path(cmd: &str, _path: &str) -> Result> { Err(bad(cmd, "paths are not available on the web; pass `data`")) diff --git a/crates/engine/src/cmd/blocks/extract.rs b/crates/engine/src/cmd/blocks/extract.rs index ecb2ca5408..7720a588e4 100644 --- a/crates/engine/src/cmd/blocks/extract.rs +++ b/crates/engine/src/cmd/blocks/extract.rs @@ -200,6 +200,7 @@ fn csv(columns: &[String], rows: &[Vec], sep: char) -> String { out } +/// Write the extracted table to `path`, held to the automation roots. fn write_file(path: &str, text: &str) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index 650bf94689..4d79a7367f 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -82,6 +82,7 @@ fn read_drawing(path: &str) -> Result { Err(last.unwrap_or_else(|| bad("insert", format!("{path}: file not found")))) } +/// The bytes of the drawing to insert, held to the automation roots. fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/engine/src/cmd/blocks/xref.rs b/crates/engine/src/cmd/blocks/xref.rs index c5be66c70b..832c1bc85f 100644 --- a/crates/engine/src/cmd/blocks/xref.rs +++ b/crates/engine/src/cmd/blocks/xref.rs @@ -353,6 +353,7 @@ fn run_xbind(s: &mut Session, p: &Value) -> Result { Ok(json!({ "bound": bound })) } +/// Open the file a selected reference points at, as its own drawing. fn run_xopen(s: &mut Session, p: &Value) -> Result { let d = s.doc()?; let name = match str_param(p, "name") { diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index fe03b5d5d2..bdd71e7f0c 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -150,6 +150,7 @@ pub(crate) enum Missing { } impl Missing { + /// The status and message a reference gets when its file can't be loaded. fn outcome(self, path: &str) -> (XrefStatus, String) { match self { Self::NotFound => { diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index a395390db1..d5562621e5 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -202,6 +202,7 @@ fn import_drawing(s: &mut Session, src: &Drawing, at: Vec2, scale: f64, file: &s })) } +/// The bytes of the file to import, held to the automation roots. fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 0d17665cc5..331fedf79e 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -330,6 +330,7 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result { Ok(opened(s, i, true)) } +/// Parse a drawing's bytes, and search its folder for fonts where the automation roots allow. fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result { let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?; let drawing = (hooks.read)(bytes, name).map_err(|e| bad("open", e))?; diff --git a/crates/engine/src/cmd/file/compare.rs b/crates/engine/src/cmd/file/compare.rs index 2b0b2678ad..518e79829c 100644 --- a/crates/engine/src/cmd/file/compare.rs +++ b/crates/engine/src/cmd/file/compare.rs @@ -107,6 +107,7 @@ fn other_drawing(s: &Session, p: &Value) -> Result<(Arc, String)> { Ok((Arc::new(d), name)) } +/// The bytes of the drawing to compare with, held to the automation roots. fn read_path(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/engine/src/cmd/file/template.rs b/crates/engine/src/cmd/file/template.rs index 0134f2e9ff..be09af71c1 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -78,6 +78,7 @@ fn read_bytes(path: &str) -> Result> { std::fs::read(path).map_err(|e| bad("new", format!("template {path}: {e}"))) } +/// The bytes of the template at `path`, held to the automation roots. #[cfg(target_arch = "wasm32")] fn read_bytes(path: &str) -> Result> { Err(bad("new", format!("template {path}: paths are not available on the web"))) diff --git a/crates/engine/src/cmd/helpers.rs b/crates/engine/src/cmd/helpers.rs index b689900488..ad9d5aaf7f 100644 --- a/crates/engine/src/cmd/helpers.rs +++ b/crates/engine/src/cmd/helpers.rs @@ -127,6 +127,7 @@ fn read_support_file(cmd: &str, path: &str) -> crate::Result { Ok(String::from_utf8_lossy(&bytes).into_owned()) } +/// The text of a support file (a linetype or hatch pattern file, say), size-limited and held to the automation roots. #[cfg(target_arch = "wasm32")] fn read_support_file(cmd: &str, _path: &str) -> crate::Result { Err(super::bad(cmd, "paths are not available on the web; pass the file's contents")) diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index ef6c2edabf..7097a4739b 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -187,6 +187,7 @@ fn edit_style(cmd: &str, st: &mut PlotStyle, v: &Value) -> Result<()> { Ok(()) } +/// List, read, change, load and export plot style tables; any file is held to the automation roots. fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { let cmd = "stylesmanager"; let action = str_param(p, "action").unwrap_or("list").to_ascii_lowercase(); diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 71691d4b11..9208c2a0fc 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -556,6 +556,7 @@ fn edit_device(cmd: &str, c: &mut PlotterConfig, p: &Value) -> Result<()> { Ok(()) } +/// List, read, change, load, export and delete plotter configurations; any file is held to the automation roots. fn run_plottermanager(_s: &mut Session, p: &Value) -> Result { let cmd = "plottermanager"; let action = str_param(p, "action").unwrap_or("list").trim().to_ascii_lowercase(); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index ccaa241058..340bdc59a8 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -316,6 +316,7 @@ mod tests { assert_eq!(roots.check(s(base.join("out/new/x.png")), Access::Write), Ok(()), "a normal save inside still works"); } + /// `in2` starts like `in` and isn't inside it. #[test] fn a_sibling_with_the_same_prefix_is_outside() { let (base, roots) = folders("prefix"); @@ -324,6 +325,7 @@ mod tests { assert!(roots.check(format!("{}2/c.dxf", s(base.join("in"))), Access::Read).is_err()); } + /// `..` is followed where it can be, and refused below a missing folder. #[test] fn parent_traversal_is_resolved_or_refused() { let (base, roots) = folders("dotdot"); @@ -338,6 +340,7 @@ mod tests { assert!(e.contains("parent traversal below a folder that doesn't exist") || e.contains("outside the write root"), "{e}"); } + /// A relative path means the working directory, and an empty one is refused. #[test] fn relative_paths_resolve_against_the_working_directory() { let (_base, roots) = folders("relative"); @@ -346,6 +349,7 @@ mod tests { assert!(roots.check("", Access::Read).unwrap_err().contains("path is empty")); } + /// A root must be a folder that exists; no roots at all confines nothing. #[test] fn a_missing_root_is_an_error_and_none_is_no_confinement() { let (base, _) = folders("missing"); @@ -365,6 +369,7 @@ mod tests { assert!(e.contains("write authority is absent"), "{e}"); } + /// Links are judged by where they lead, so a link out is refused and one inside is fine. #[test] fn links_are_followed_before_comparing() { let (base, roots) = folders("links"); @@ -408,6 +413,7 @@ mod tests { assert!(same(Path::new("/w/root"), Path::new("/w/root"))); } + /// The superscript ports, `COM0`, `LPT0` and the `:` form are device names. #[test] fn device_names_include_the_superscript_ports() { for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.dxf", "NUL ", "COM¹", "lpt³.txt", "com²", "NUL:", "con:stream", "COM0", "lpt0.txt"] { @@ -452,6 +458,7 @@ mod tests { assert_eq!(roots.check(base.join("out/new/deep/x.dxf"), Access::Write), Ok(())); } + /// On a real case-sensitive folder, `Root` beside the root `root` is outside it. #[cfg(windows)] #[test] fn a_case_sensitive_windows_folder_can_hold_a_sibling_of_the_root() { @@ -472,6 +479,7 @@ mod tests { assert_eq!(roots.check(&s(base.join("root/new.dxf")), Access::Write), Ok(())); } + /// On an ordinary Windows folder any case finds the root, and device names are refused. #[cfg(windows)] #[test] fn windows_gives_a_root_its_real_spelling_and_refuses_devices() { @@ -486,6 +494,7 @@ mod tests { assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(())); } + /// Roots end with their scope, also when a nested scope or a panic ends it. #[test] fn scopes_nest_and_restore_after_a_panic() { let (base, roots) = folders("scopes"); @@ -504,6 +513,7 @@ mod tests { assert_eq!(confine(None, || check_read(&outside)), Ok(())); } + /// The plain device names, and names that only look like them. #[test] fn device_names() { for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL "] { diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index 322317e094..4ff6b992c3 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -496,6 +496,7 @@ mod tests { /// direction. const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"]; + /// The words of a command's documentation, lower case. fn words(doc: &str) -> BTreeSet { doc.to_ascii_lowercase().split(|c: char| !c.is_ascii_alphanumeric()).map(str::to_string).collect() } diff --git a/crates/engine/src/lisp/builtins/files.rs b/crates/engine/src/lisp/builtins/files.rs index 58cb1fb3a5..232c338d7c 100644 --- a/crates/engine/src/lisp/builtins/files.rs +++ b/crates/engine/src/lisp/builtins/files.rs @@ -13,6 +13,7 @@ pub struct LispFile { pub text: String, } +/// LISP `open`: a file handle, or nil when the file can't be opened or the automation roots refuse it. pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 2, 3)?; let path = string(&a[0])?.to_string(); @@ -98,6 +99,7 @@ fn can_write(_path: &str) -> bool { false } +/// Write or append `text`, doing nothing when the automation roots refuse the path. #[cfg(not(target_arch = "wasm32"))] fn write_text_file(path: &str, text: &str, append: bool) { use std::io::Write; @@ -113,6 +115,7 @@ fn write_text_file(path: &str, text: &str, append: bool) { #[cfg(target_arch = "wasm32")] fn write_text_file(_path: &str, _text: &str, _append: bool) {} +/// Whether a file is at `path`; outside the automation roots the answer is no. #[cfg(not(target_arch = "wasm32"))] fn file_exists(path: &str) -> bool { crate::file_access::check_read(path).is_ok() && std::path::Path::new(path).is_file() diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 6f71b25372..74e2a9f6ee 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -24,6 +24,7 @@ impl Session { } } + /// Run a command by id, unless the automation roots, its own state or the block editor refuse it. fn execute_guarded(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; if let Some(why) = crate::file_access::commands::refusal(spec.id) { diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 0cd9020219..eb2182d0b6 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -286,6 +286,7 @@ pub fn format_angle_list(angles: &[f64]) -> String { angles.iter().map(|a| format!("{}", (a.to_degrees() * 1e6).round() / 1e6)).collect::>().join(";") } +/// Set a system variable, refusing values out of its range and folders the automation roots can't hold. pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { let n = name.trim().to_ascii_uppercase(); if is_read_only(&n) { diff --git a/crates/engine/tests/dash_wblock.rs b/crates/engine/tests/dash_wblock.rs index b4c2f7f670..d19fcc60fa 100644 --- a/crates/engine/tests/dash_wblock.rs +++ b/crates/engine/tests/dash_wblock.rs @@ -285,6 +285,7 @@ fn oops_brings_back_what_it_erased_where_it_was() { assert_eq!(order, [a, b, c]); } +/// A refused -WBLOCK leaves OOPS as it was. #[test] fn a_dash_wblock_refused_during_refedit_leaves_oops_as_it_was() { let (mut s, a, b, c) = drawing(); diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index c74599b779..de7a4b9573 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -342,6 +342,7 @@ fn state(s: &Session) -> Value { } impl Headless { + /// The reply to one control method; the caller holds it to the roots. fn answer(&mut self, method: &str, p: &Value) -> Result { let s = &mut self.session; let str_p = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); @@ -462,6 +463,7 @@ impl Headless { } impl Backend for Headless { + /// Run one control method inside the roots, if any. fn call(&mut self, method: &str, p: Value) -> Result { let roots = self.roots.clone(); file_access::confine(roots.as_ref(), || self.answer(method, &p)) @@ -469,6 +471,7 @@ impl Backend for Headless { fn has_ui(&self) -> bool { false } + /// What this backend talks to, for messages. fn describe(&self) -> String { "headless CADCraft session".into() } From 8a42e8a1ac2f7f9ec7ea5b97737c5f994cde0743 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:33:34 +0000 Subject: [PATCH 09/27] Refuse a network path before the automation roots open it A UNC, device or non-disk verbatim path was canonicalized before the roots refused it, so on Windows the machine contacted a host the agent chose. Those prefixes are refused first, unless a root is already on the same server and share. A link that leads to one is refused from the link's text, including when the link is only an ancestor of the name. The Windows tests drop the borrows clippy rejects, and cover a junction, an alternate stream and a Kelvin-sign name. The command walk also notices a new file when the folder's modification time has not moved. --- apps/cadcraft-cli/tests/mcp_roots.rs | 26 ++ apps/cadcraft-cli/tests/mcp_roots_walk.rs | 25 +- crates/engine/src/file_access.rs | 277 ++++++++++++++++++++-- docs/mcp.md | 11 +- 4 files changed, 315 insertions(+), 24 deletions(-) diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs index 6011842b9f..d83746c279 100644 --- a/apps/cadcraft-cli/tests/mcp_roots.rs +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -373,3 +373,29 @@ fn missing_roots_and_roots_with_connect_fail_at_startup() { assert!(!out.status.success() && out.stdout.is_empty()); assert!(String::from_utf8_lossy(&out.stderr).contains("headless MCP server")); } + +/// A UNC, device or non-disk verbatim path is refused by the server before it is opened. +/// The reply names the prefix. It is not an operating-system error from opening the path. +#[cfg(windows)] +#[test] +fn a_network_path_is_refused_before_it_is_opened() { + let base = folders("unc"); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[ + ("open", json!({"path": r"\\203.0.113.5\s\x.dwg"})), + ("open", json!({"path": r"\\?\UNC\203.0.113.5\s\x.dwg"})), + ("open", json!({"path": r"\\host@SSL\share\x.dwg"})), + ("open", json!({"path": r"\\.\PhysicalDrive0"})), + ("open", json!({"path": r"\\?\Volume{00000000-0000-0000-0000-000000000000}\x.dwg"})), + ("execute", json!({"command": "circle", "params": {"center": [0, 0], "radius": 1}})), + ], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + let kinds = ["UNC", "UNC", "UNC", "device path", "verbatim path"]; + for (tool, kind) in t.iter().zip(kinds) { + refused(tool, kind); + assert!(!tool.text.contains("cannot resolve") && !tool.text.to_ascii_lowercase().contains("os error"), "{}", tool.text); + } + ok(&t[5]); +} diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index d74c71631a..1ed831e317 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -1,7 +1,8 @@ //! Walks every command in the registry through the real MCP server with paths outside the -//! automation roots (#1472). Reads show as a changed access time and writes as a changed size, -//! modification time or folder, whatever the command does with the path. The same walk without -//! roots has to find escapes, or finding none under roots would prove nothing. +//! automation roots (#1472). Reads show as a changed access time and writes as a changed size or +//! modification time, a removed file, or a file that was not there before, whatever the command +//! does with the path. The same walk without roots has to find escapes, or finding none under +//! roots would prove nothing. #![cfg(unix)] // Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Never crash). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -206,12 +207,13 @@ impl Fixture { } } - /// What happened under `outside` since [`Self::reset`]. Only metadata is read: this leaves - /// the access times as they are. + /// What happened under `outside` since [`Self::reset`]. Metadata is read before any directory + /// listing, and directory access times are put back afterwards: the listing is how a new file + /// is seen when the folder's modification time has not moved, and it must not look like a read. fn touched(&self) -> Vec { let mut seen = Vec::new(); for (p, (len, modified, accessed)) in &self.baseline { - let name = p.strip_prefix(&self.outside).unwrap().display(); + let name = p.strip_prefix(&self.outside).unwrap_or(p).display(); match std::fs::metadata(p) { Err(_) => seen.push(format!("removed {name}")), Ok(m) if m.modified().unwrap() != *modified || (!m.is_dir() && m.len() != *len) => seen.push(format!("wrote {name}")), @@ -219,6 +221,17 @@ impl Fixture { Ok(_) => {} } } + for p in tree(&self.outside) { + if !self.baseline.contains_key(&p) { + let name = p.strip_prefix(&self.outside).unwrap_or(&p).display(); + seen.push(format!("created {name}")); + } + } + for (p, (_, _, accessed)) in &self.baseline { + if p.is_dir() { + let _ = File::open(p).and_then(|f| f.set_times(FileTimes::new().set_accessed(*accessed))); + } + } seen } } diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 340bdc59a8..706d414e82 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -9,6 +9,11 @@ //! links are followed: for a file that doesn't exist yet, the links of its nearest existing //! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so //! is a link that leads nowhere). +//! - On Windows a network path (`\\server\share`, `\\?\UNC\...`), a device path (`\\.\...`) or a +//! verbatim path that isn't a disk is refused before anything opens it, unless a root is already +//! on that same server and share (or that same device or prefix). A link whose target is one of +//! those is refused from the target text, before the link is followed. Opening such a path would +//! contact a host the agent named. //! - The result must lie inside the root, compared by whole components (`/work2` isn't inside //! `/work`) and exactly: both sides have been through the file system, which gives each folder //! its real name, and a Windows folder can be case sensitive, with `Root` beside `root`. @@ -20,8 +25,9 @@ //! it; without roots nothing is checked, so the app and the command line keep working everywhere. //! //! A path is checked, then opened: a process that can change the folders in between (swapping in -//! a link) can still win that race. The roots keep an agent to the files it was given; they don't -//! guard against other programs on the computer. +//! a link) can still win that race. A network, device or non-disk verbatim path is not opened at +//! all. The roots keep an agent to the files it was given; they don't guard against other +//! programs on the computer. pub mod commands; @@ -90,7 +96,7 @@ impl AutomationRoots { /// different file. pub fn check(&self, given: impl AsRef, access: Access) -> Result<(), String> { let given = given.as_ref(); - let target = resolve(given)?; + let target = resolve(given, self)?; let path = given.display(); if access == Access::Read { let roots = [self.read.as_ref(), self.write.as_ref()]; @@ -112,7 +118,7 @@ impl AutomationRoots { if same(&target, folder) { return Err(format!("automation path rejected: the write root itself cannot be written: {path}")); } - if !inside(&resolve(given.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")))?, folder) { + if !inside(&resolve(given.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")), self)?, folder) { return Err(format!("automation path rejected: stands outside the write root {}: {path}", folder.display())); } Ok(()) @@ -157,7 +163,10 @@ pub fn check_write(path: impl AsRef) -> Result<(), String> { /// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest /// existing folder's links followed and the rest appended. -fn resolve(path: &Path) -> Result { +/// +/// A Windows network, device or non-disk verbatim prefix is refused before any of that, unless +/// `roots` already stands on the same server and share (or the same device or prefix). +fn resolve(path: &Path, roots: &AutomationRoots) -> Result { let shown = path.display(); if path.as_os_str().is_empty() { return Err("automation path rejected: path is empty".into()); @@ -166,11 +175,23 @@ fn resolve(path: &Path) -> Result { if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if n.to_str().is_some_and(is_device_name))) { return Err(format!("automation path rejected: reserved device names are not allowed: {shown}")); } + // Before `absolute` too: on Windows that call asks the system about the path. + if let Some(why) = refused_prefix(path, roots) { + return Err(format!("automation path rejected: {why}: {shown}")); + } let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))?; + if let Some(why) = refused_prefix(&absolute, roots) { + return Err(format!("automation path rejected: {why}: {shown}")); + } // The names below the nearest existing folder, last first. let mut missing: Vec = vec![]; let mut at = absolute.as_path(); loop { + // A link to a network path is judged from the target text. Canonicalizing it would follow + // the link and contact that host. + if let Some(why) = link_leads_to_refused_prefix(at, roots) { + return Err(format!("automation path rejected: {why}: {shown}")); + } match std::fs::canonicalize(at) { Ok(mut found) => { found.extend(missing.iter().rev()); @@ -202,6 +223,136 @@ fn resolve(path: &Path) -> Result { } } +/// Why `path` must not be opened: it is a Windows network, device or non-disk verbatim path, and +/// no root already uses that prefix. A local disk path returns `None`. +/// +/// The comparison is ASCII case only, so `FileServer` matches `fileserver` and U+212A does not +/// match `k`. Matching only decides whether that host may be contacted; [`inside`] still decides +/// the folder. +fn refused_prefix(path: &Path, roots: &AutomationRoots) -> Option<&'static str> { + #[cfg(windows)] + { + let key = windows_prefix(path)?; + let allowed = [roots.read.as_ref(), roots.write.as_ref()] + .into_iter() + .flatten() + .any(|root| windows_prefix(root).is_some_and(|root_key| prefixes_match(&root_key, &key))); + if allowed { None } else { Some(key.refusal()) } + } + #[cfg(not(windows))] + { + let _ = (path, roots); + None + } +} + +/// The refusal for a link in `path`, taken from the link's own text. +/// +/// Folders are inspected from the root downward with [`std::fs::symlink_metadata`], which does not +/// follow a link, and the target is read with [`std::fs::read_link`]. A link to a network path is +/// therefore refused before [`std::fs::canonicalize`] would open that host, including when the +/// link is only an ancestor of the name. At most [`MAX_LINK_HOPS`] links are followed. +fn link_leads_to_refused_prefix(path: &Path, roots: &AutomationRoots) -> Option<&'static str> { + follow_links(path, roots, MAX_LINK_HOPS) +} + +/// [`link_leads_to_refused_prefix`], with `hops_left` links still allowed. +fn follow_links(path: &Path, roots: &AutomationRoots, hops_left: usize) -> Option<&'static str> { + if let Some(why) = refused_prefix(path, roots) { + return Some(why); + } + let mut ancestors: Vec<&Path> = path.ancestors().collect(); + ancestors.reverse(); + for prefix in ancestors { + // A relative path's ancestor list ends at an empty name. Absolute paths, which are all + // this is called with, have no empty ancestor; skip it rather than treating it as missing. + if prefix.as_os_str().is_empty() { + continue; + } + if let Some(why) = refused_prefix(prefix, roots) { + return Some(why); + } + let Ok(meta) = std::fs::symlink_metadata(prefix) else { return None }; + if !meta.file_type().is_symlink() { + continue; + } + if hops_left == 0 { + return None; + } + let Ok(target) = std::fs::read_link(prefix) else { return None }; + let joined = if target.is_absolute() { + target + } else { + match prefix.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent.join(target), + _ => target, + } + }; + let rest = match path.strip_prefix(prefix) { + Ok(rest) if !rest.as_os_str().is_empty() => rest, + _ => Path::new(""), + }; + let next = if rest.as_os_str().is_empty() { joined } else { joined.join(rest) }; + if let Some(why) = refused_prefix(&next, roots) { + return Some(why); + } + return follow_links(&next, roots, hops_left - 1); + } + None +} + +/// How many links [`link_leads_to_refused_prefix`] follows before it stops. +const MAX_LINK_HOPS: usize = 40; + +/// A Windows prefix that is not a local disk. +#[cfg(windows)] +enum WindowsPrefix { + /// `\\server\share` or `\\?\UNC\server\share`. + Unc(OsString, OsString), + /// `\\.\device`. + Device(OsString), + /// `\\?\` that is neither a disk nor `UNC`. + Verbatim(OsString), +} + +#[cfg(windows)] +impl WindowsPrefix { + /// The error text for a path with this prefix. + fn refusal(&self) -> &'static str { + match self { + Self::Unc(_, _) => "UNC paths are refused unless a root is on the same server and share", + Self::Device(_) => "device paths are refused unless a root uses the same device", + Self::Verbatim(_) => "verbatim paths are refused unless a root uses the same prefix", + } + } +} + +/// `path`'s Windows prefix when it is not a local disk. +#[cfg(windows)] +fn windows_prefix(path: &Path) -> Option { + use std::path::Prefix; + let Component::Prefix(prefix) = path.components().next()? else { return None }; + match prefix.kind() { + Prefix::Disk(_) | Prefix::VerbatimDisk(_) => None, + Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => Some(WindowsPrefix::Unc(server.to_os_string(), share.to_os_string())), + Prefix::DeviceNS(device) => Some(WindowsPrefix::Device(device.to_os_string())), + Prefix::Verbatim(rest) => Some(WindowsPrefix::Verbatim(rest.to_os_string())), + } +} + +/// Whether `path` may be opened because `root` already stands on the same server and share, +/// device or verbatim prefix. ASCII case only. +#[cfg(windows)] +fn prefixes_match(root: &WindowsPrefix, path: &WindowsPrefix) -> bool { + let same = |a: &std::ffi::OsStr, b: &std::ffi::OsStr| a.eq_ignore_ascii_case(b); + match (root, path) { + (WindowsPrefix::Unc(server, share), WindowsPrefix::Unc(path_server, path_share)) => same(server, path_server) && same(share, path_share), + (WindowsPrefix::Device(root_device), WindowsPrefix::Device(path_device)) => same(root_device, path_device), + (WindowsPrefix::Verbatim(root_prefix), WindowsPrefix::Verbatim(path_prefix)) => same(root_prefix, path_prefix), + _ => false, + } +} + /// Is `path` (resolved) `root` or inside it, component by component? fn inside(path: &Path, root: &Path) -> bool { let mut path = path.components(); @@ -473,10 +624,10 @@ mod tests { std::fs::write(base.join("Root/secret.dxf"), "x").unwrap(); let roots = AutomationRoots::new(Some(&base.join("root")), Some(&base.join("root"))).unwrap().unwrap(); for p in ["Root/secret.dxf", "Root/new.dxf"] { - assert!(roots.check(&s(base.join(p)), Access::Read).is_err(), "{p}"); - assert!(roots.check(&s(base.join(p)), Access::Write).is_err(), "{p}"); + assert!(roots.check(s(base.join(p)), Access::Read).is_err(), "{p}"); + assert!(roots.check(s(base.join(p)), Access::Write).is_err(), "{p}"); } - assert_eq!(roots.check(&s(base.join("root/new.dxf")), Access::Write), Ok(())); + assert_eq!(roots.check(s(base.join("root/new.dxf")), Access::Write), Ok(())); } /// On an ordinary Windows folder any case finds the root, and device names are refused. @@ -485,13 +636,111 @@ mod tests { fn windows_gives_a_root_its_real_spelling_and_refuses_devices() { let (base, roots) = folders("case"); let upper = s(base.join("IN/A.DXF")); - assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}"); - assert_eq!(roots.check(&s(base.join("In/Sub/New.dxf")), Access::Read), Ok(())); - let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err(); + assert_eq!(roots.check(upper.as_str(), Access::Read), Ok(()), "{upper}"); + assert_eq!(roots.check(s(base.join("In/Sub/New.dxf")), Access::Read), Ok(())); + let e = roots.check(s(base.join("out/NUL")), Access::Write).unwrap_err(); assert!(e.contains("reserved device names"), "{e}"); - assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err()); - assert!(roots.check(&s(base.join("out/COM¹")), Access::Write).is_err()); - assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(())); + assert!(roots.check(s(base.join("out/com1.txt")), Access::Write).is_err()); + assert!(roots.check(s(base.join("out/COM¹")), Access::Write).is_err()); + assert_eq!(roots.check(s(base.join("out/console.txt")), Access::Write), Ok(())); + } + + /// A network, device or non-disk verbatim path is refused before the file system is asked. + /// The error names the prefix. It is not the error canonicalize would return. + #[cfg(windows)] + #[test] + fn a_network_path_is_refused_before_it_is_opened() { + let (base, roots) = folders("unc"); + let paths = [ + (r"\\203.0.113.5\s\x.dwg", "UNC"), + (r"\\?\UNC\203.0.113.5\s\x.dwg", "UNC"), + (r"//203.0.113.5/s/x.dwg", "UNC"), + (r"\\host@SSL\share\x.dwg", "UNC"), + (r"\\host@SSL@443\share\x.dwg", "UNC"), + (r"\\.\PhysicalDrive0", "device path"), + (r"\\?\Volume{00000000-0000-0000-0000-000000000000}\x.dwg", "verbatim path"), + ]; + for (p, kind) in paths { + for access in [Access::Read, Access::Write] { + let e = roots.check(p, access).unwrap_err(); + assert!(e.starts_with("automation path rejected:"), "{p}: {e}"); + assert!(e.contains(kind), "{p}: {e}"); + assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{p}: {e}"); + } + } + let e = roots.check(s(base.join("outside/secret.dxf")), Access::Read).unwrap_err(); + assert!(e.contains("outside the read root"), "{e}"); + + let root = windows_prefix(Path::new(r"\\?\UNC\FileServer\Projects\work")).unwrap(); + let same = windows_prefix(Path::new(r"\\fileserver\projects\a.dwg")).unwrap(); + let other_share = windows_prefix(Path::new(r"\\fileserver\secret\a.dwg")).unwrap(); + let other_host = windows_prefix(Path::new(r"\\203.0.113.5\Projects\a.dwg")).unwrap(); + let kelvin = windows_prefix(Path::new(&format!("\\\\wor\u{212a}\\Projects\\a.dwg"))).unwrap(); + assert!(prefixes_match(&root, &same), "the same server and share, in either spelling"); + assert!(!prefixes_match(&root, &other_share)); + assert!(!prefixes_match(&root, &other_host)); + assert!(!prefixes_match(&root, &kelvin), "U+212A is not k"); + assert!(windows_prefix(Path::new(r"C:\Projects\a.dwg")).is_none()); + assert!(windows_prefix(Path::new(r"\\?\C:\Projects\a.dwg")).is_none()); + } + + /// U+212A is a different folder from `k`, so a write there is outside the root and creates nothing. + #[cfg(windows)] + #[test] + fn a_kelvin_sign_is_not_a_way_out_of_the_write_root() { + let base = fresh_dir("kelvin"); + let root = base.join("work"); + std::fs::create_dir(&root).unwrap(); + let roots = AutomationRoots::new(Some(&root), Some(&root)).unwrap().unwrap(); + let sibling = base.join(format!("wor\u{212a}")).join("x.dwg"); + let e = roots.check(s(sibling), Access::Write).unwrap_err(); + assert!(e.contains("outside the write root"), "{e}"); + assert!(!base.join(format!("wor\u{212a}")).exists(), "the check must not create the folder"); + assert_eq!(roots.check(s(root.join("new.dxf")), Access::Write), Ok(())); + } + + /// A junction needs no extra privilege. One that leads out of the write root is outside it. + #[cfg(windows)] + #[test] + fn a_junction_out_of_the_write_root_is_refused() { + let (base, roots) = folders("junction"); + let link = base.join("out/away"); + let made = std::process::Command::new("cmd") + .arg("/c") + .arg(format!("mklink /J \"{}\" \"{}\"", link.display(), base.join("outside").display())) + .status(); + if !made.is_ok_and(|s| s.success()) { + eprintln!("skipped: junctions can't be made here"); + return; + } + let e = roots.check(s(base.join("out/away/new.png")), Access::Write).unwrap_err(); + assert!(e.contains("outside the write root"), "{e}"); + assert!(!base.join("outside/new.png").exists()); + } + + /// A link whose text names a network path is refused before that path is opened. + #[cfg(windows)] + #[test] + fn a_link_to_a_network_path_is_refused_before_it_is_followed() { + let (base, roots) = folders("unc-link"); + let link = base.join("in/leak.dxf"); + if std::os::windows::fs::symlink_file(r"\\203.0.113.5\s\x.dwg", &link).is_err() { + eprintln!("skipped: symbolic links can't be made here"); + return; + } + let e = roots.check(link.as_path(), Access::Read).unwrap_err(); + assert!(e.contains("UNC"), "{e}"); + assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}"); + } + + /// An alternate data stream is still the file it hangs off: outside the roots it is refused. + #[cfg(windows)] + #[test] + fn an_alternate_stream_outside_the_roots_is_refused() { + let (base, roots) = folders("ads"); + let e = roots.check(s(base.join("outside/secret.dxf:zone")), Access::Read).unwrap_err(); + assert!(e.contains("outside the read root"), "{e}"); + assert_eq!(roots.check(s(base.join("out/new.dxf:zone")), Access::Write), Ok(())); } /// Roots end with their scope, also when a nested scope or a panic ends it. diff --git a/docs/mcp.md b/docs/mcp.md index d12a77988d..3c0b4f67e0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -60,16 +60,19 @@ configuration works across the suite) keep the agent to the folders you give it: a folder that doesn't exist is refused, as is a link that leads nowhere. The result is compared with the root by whole folder names, exactly: `/work2/x` is not inside `/work`, and on Windows a folder's own case comes from the file system, so a case-sensitive folder's `Root` is not - `root`. On Windows UNC paths are resolved like drive-letter ones, and device names (`CON`, `NUL`, - `COM1`, `LPT¹`…) are refused. + `root`. On Windows a UNC path (`\\server\share`, `\\?\UNC\...`, including `\\host@SSL\...`), a + device path (`\\.\...`) or a verbatim path that isn't a disk is refused before it is opened, + unless a root is already on that same server and share. Device names (`CON`, `NUL`, `COM1`, + `LPT¹`…) are refused too. - A path you write must also stand under the write root: a link outside it pointing in is refused, because a drawing's `.bak` goes beside the link and a delete removes the link. - A refused path is an ordinary tool error with `isError: true` that the agent can read and correct, for example `automation path rejected: outside the write root /work/project/out: /etc/x.png`, `automation path rejected: outside the read root (or the write root): /etc/x.png`, `automation path rejected: the write root itself cannot be written: - /work/project/out`, or `automation filesystem access is not granted: write authority is absent: - /work/project/out/x.png`. + /work/project/out`, `automation path rejected: UNC paths are refused unless a root is on the + same server and share: \\203.0.113.5\s\x.dwg`, or `automation filesystem access is not granted: + write authority is absent: /work/project/out/x.png`. - A file a drawing names is held to the roots too: an image or xref saved with a path outside them stays unloaded, and the answer doesn't say whether the file exists. - A command runs under the roots only if it is classified (`crates/engine/src/file_access/commands.rs`): From 578564403a44b5d4ba69654c50a93500de0f8dc4 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:12:30 +0000 Subject: [PATCH 10/27] Fix the Windows clippy lints and the junction test, and state each prefix rule The three format! calls in the Windows tests are string literals, which is what clippy asks for there. The junction test passes mklink's arguments separately and builds the link path with a real separator, so the junction is created and the refusal is what the test checks. The link walk runs only on Windows, and it refuses a link it cannot read and a chain longer than the limit instead of handing either to canonicalize. The MCP notes say a UNC path needs the same server and share, a device path the same device, and a verbatim path the same prefix. --- crates/engine/src/file_access.rs | 29 ++++++++++++++++------------- docs/mcp.md | 7 ++++--- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 706d414e82..1a3d46b4c4 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -188,7 +188,9 @@ fn resolve(path: &Path, roots: &AutomationRoots) -> Result { let mut at = absolute.as_path(); loop { // A link to a network path is judged from the target text. Canonicalizing it would follow - // the link and contact that host. + // the link and contact that host. Only Windows has those prefixes, so other targets skip + // the walk. + #[cfg(windows)] if let Some(why) = link_leads_to_refused_prefix(at, roots) { return Err(format!("automation path rejected: {why}: {shown}")); } @@ -251,12 +253,15 @@ fn refused_prefix(path: &Path, roots: &AutomationRoots) -> Option<&'static str> /// Folders are inspected from the root downward with [`std::fs::symlink_metadata`], which does not /// follow a link, and the target is read with [`std::fs::read_link`]. A link to a network path is /// therefore refused before [`std::fs::canonicalize`] would open that host, including when the -/// link is only an ancestor of the name. At most [`MAX_LINK_HOPS`] links are followed. +/// link is only an ancestor of the name. At most [`MAX_LINK_HOPS`] links are followed; one more, +/// or a link whose target cannot be read, is refused instead of being opened. +#[cfg(windows)] fn link_leads_to_refused_prefix(path: &Path, roots: &AutomationRoots) -> Option<&'static str> { follow_links(path, roots, MAX_LINK_HOPS) } /// [`link_leads_to_refused_prefix`], with `hops_left` links still allowed. +#[cfg(windows)] fn follow_links(path: &Path, roots: &AutomationRoots, hops_left: usize) -> Option<&'static str> { if let Some(why) = refused_prefix(path, roots) { return Some(why); @@ -277,9 +282,9 @@ fn follow_links(path: &Path, roots: &AutomationRoots, hops_left: usize) -> Optio continue; } if hops_left == 0 { - return None; + return Some("too many links"); } - let Ok(target) = std::fs::read_link(prefix) else { return None }; + let Ok(target) = std::fs::read_link(prefix) else { return Some("a link that leads nowhere") }; let joined = if target.is_absolute() { target } else { @@ -302,6 +307,7 @@ fn follow_links(path: &Path, roots: &AutomationRoots, hops_left: usize) -> Optio } /// How many links [`link_leads_to_refused_prefix`] follows before it stops. +#[cfg(windows)] const MAX_LINK_HOPS: usize = 40; /// A Windows prefix that is not a local disk. @@ -675,7 +681,7 @@ mod tests { let same = windows_prefix(Path::new(r"\\fileserver\projects\a.dwg")).unwrap(); let other_share = windows_prefix(Path::new(r"\\fileserver\secret\a.dwg")).unwrap(); let other_host = windows_prefix(Path::new(r"\\203.0.113.5\Projects\a.dwg")).unwrap(); - let kelvin = windows_prefix(Path::new(&format!("\\\\wor\u{212a}\\Projects\\a.dwg"))).unwrap(); + let kelvin = windows_prefix(Path::new("\\\\wor\u{212a}\\Projects\\a.dwg")).unwrap(); assert!(prefixes_match(&root, &same), "the same server and share, in either spelling"); assert!(!prefixes_match(&root, &other_share)); assert!(!prefixes_match(&root, &other_host)); @@ -692,10 +698,10 @@ mod tests { let root = base.join("work"); std::fs::create_dir(&root).unwrap(); let roots = AutomationRoots::new(Some(&root), Some(&root)).unwrap().unwrap(); - let sibling = base.join(format!("wor\u{212a}")).join("x.dwg"); + let sibling = base.join("wor\u{212a}").join("x.dwg"); let e = roots.check(s(sibling), Access::Write).unwrap_err(); assert!(e.contains("outside the write root"), "{e}"); - assert!(!base.join(format!("wor\u{212a}")).exists(), "the check must not create the folder"); + assert!(!base.join("wor\u{212a}").exists(), "the check must not create the folder"); assert_eq!(roots.check(s(root.join("new.dxf")), Access::Write), Ok(())); } @@ -704,16 +710,13 @@ mod tests { #[test] fn a_junction_out_of_the_write_root_is_refused() { let (base, roots) = folders("junction"); - let link = base.join("out/away"); - let made = std::process::Command::new("cmd") - .arg("/c") - .arg(format!("mklink /J \"{}\" \"{}\"", link.display(), base.join("outside").display())) - .status(); + let link = base.join("out").join("away"); + let made = std::process::Command::new("cmd").args(["/c", "mklink", "/J"]).arg(&link).arg(base.join("outside")).status(); if !made.is_ok_and(|s| s.success()) { eprintln!("skipped: junctions can't be made here"); return; } - let e = roots.check(s(base.join("out/away/new.png")), Access::Write).unwrap_err(); + let e = roots.check(s(link.join("new.png")), Access::Write).unwrap_err(); assert!(e.contains("outside the write root"), "{e}"); assert!(!base.join("outside/new.png").exists()); } diff --git a/docs/mcp.md b/docs/mcp.md index 3c0b4f67e0..61b33c2f66 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -60,9 +60,10 @@ configuration works across the suite) keep the agent to the folders you give it: a folder that doesn't exist is refused, as is a link that leads nowhere. The result is compared with the root by whole folder names, exactly: `/work2/x` is not inside `/work`, and on Windows a folder's own case comes from the file system, so a case-sensitive folder's `Root` is not - `root`. On Windows a UNC path (`\\server\share`, `\\?\UNC\...`, including `\\host@SSL\...`), a - device path (`\\.\...`) or a verbatim path that isn't a disk is refused before it is opened, - unless a root is already on that same server and share. Device names (`CON`, `NUL`, `COM1`, + `root`. On Windows a UNC path (`\\server\share`, `\\?\UNC\...`, including `\\host@SSL\...`) is + refused before it is opened unless a root is on that same server and share. A device path + (`\\.\...`) is refused unless a root uses the same device, and a verbatim path that isn't a + disk is refused unless a root uses the same prefix. Device names (`CON`, `NUL`, `COM1`, `LPT¹`…) are refused too. - A path you write must also stand under the write root: a link outside it pointing in is refused, because a drawing's `.bak` goes beside the link and a delete removes the link. From 387a6e6b1e618801ca9d8d78baa6410be3941909 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:37:50 +0530 Subject: [PATCH 11/27] Check each font the search would open under the roots, and say what command_line returns on a refusal The font search opened a candidate by name, so a link under a name the .shx filter missed (or a Windows short name for one) was followed out of the roots. A drawing folder now carries a guard that the search asks about every file before opening it; the roots supply it, and a link is judged by where it leads. One font leading out no longer disables the others beside it. Documents that a refusal inside command_line comes back in the reply's error field without isError, and adds doc comments to the remaining functions the change touches. --- apps/cadcraft-cli/tests/mcp_roots.rs | 2 + apps/cadcraft-cli/tests/mcp_roots_walk.rs | 37 +++++++++++ crates/engine/src/cmd/audit.rs | 1 + crates/engine/src/cmd/file.rs | 23 +++---- crates/engine/src/cmd/file/template.rs | 1 + crates/engine/src/cmd/helpers.rs | 1 + crates/engine/src/file_access.rs | 3 + crates/fonts/src/shx/mod.rs | 4 +- crates/fonts/src/shx/table.rs | 75 ++++++++++++++++++----- crates/fonts/tests/shx_guard.rs | 54 ++++++++++++++++ crates/mcp/src/backend.rs | 1 + docs/mcp.md | 9 +-- 12 files changed, 174 insertions(+), 37 deletions(-) create mode 100644 crates/fonts/tests/shx_guard.rs diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs index d83746c279..f3c21904af 100644 --- a/apps/cadcraft-cli/tests/mcp_roots.rs +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -18,12 +18,14 @@ struct TestDir(PathBuf); impl std::ops::Deref for TestDir { type Target = Path; + /// The folder itself. fn deref(&self) -> &Path { &self.0 } } impl Drop for TestDir { + /// Removes the folder and all it holds; a failure here must not hide the test's own. fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index 1ed831e317..f4c0032f78 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -101,6 +101,7 @@ impl Server { } impl Drop for Server { + /// Stops the server it started. fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); @@ -237,6 +238,7 @@ impl Fixture { } impl Drop for Fixture { + /// Removes the fixture folder when the test ends, also when it fails. fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.base); } @@ -686,6 +688,41 @@ fn a_font_beside_a_drawing_inside_the_roots_is_used() { } } +/// One font that is a link leading out doesn't cost the drawing the other fonts beside it, and +/// nothing outside is touched. +#[test] +fn a_font_link_leading_out_does_not_cost_the_fonts_beside_it() { + let mut f = Fixture::new("font-mixed"); + let host = f.base.join("in/host.dxf"); + { + let mut free = Server::start(&[], &f.outside.join("cwd"), &f.outside.join("config")); + free.execute("new", json!({})).unwrap(); + for (style, font) in [("Good", "walkgood.shx"), ("Bad", "walkbad.shx")] { + free.execute("style", json!({"name": style, "font": font})).unwrap(); + free.execute("style.current", json!({"name": style})).unwrap(); + free.execute("text", json!({"at": [0, 0], "height": 5, "text": style})).unwrap(); + } + free.execute("saveas", json!({"path": s(&host)})).unwrap(); + } + let good = f.base.join("in/walkgood.shx"); + std::fs::write(&good, b"AutoCAD-86 shapes 1.0").unwrap(); + age_access_time(&good); + let before = std::fs::metadata(&good).unwrap().accessed().unwrap(); + let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))]; + let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config")); + f.reset(); + std::fs::write(f.outside.join("walkbad.shx"), b"AutoCAD-86 shapes 1.0").unwrap(); + std::os::unix::fs::symlink(f.outside.join("walkbad.shx"), f.base.join("in/walkbad.shx")).unwrap(); + f.watch(); + server.tool("open", json!({"path": s(&host)})).unwrap(); + server.tool("render", json!({})).unwrap(); + let touched = f.touched(); + assert!(touched.is_empty(), "{touched:?}"); + if f.sees_reads { + assert_ne!(std::fs::metadata(&good).unwrap().accessed().unwrap(), before, "the good font was read"); + } +} + /// The fixture leaves the server's working directory in place, so a relative path meets the roots /// and not a folder that has gone. #[test] diff --git a/crates/engine/src/cmd/audit.rs b/crates/engine/src/cmd/audit.rs index fd24871b2b..cc37505671 100644 --- a/crates/engine/src/cmd/audit.rs +++ b/crates/engine/src/cmd/audit.rs @@ -161,6 +161,7 @@ fn write_audit_log(s: &Session, report: &crate::audit::Report) { fn write_audit_log(_: &Session, _: &crate::audit::Report) {} #[cfg(not(target_arch = "wasm32"))] +/// The bytes of the file at `path`, once the automation roots allow reading it. fn read_path(cmd: &str, path: &str) -> Result> { crate::file_access::check_read(path).map_err(|e| bad(cmd, e))?; crate::capped_read::read_capped(std::path::Path::new(path), file::MAX_DRAWING_BYTES).map_err(|e| bad(cmd, format!("{path}: {e}"))) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 234b2c2023..c5a025bb54 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -341,25 +341,20 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result cadcraft_fonts::shx::add_drawing_dir(&dir), + // The folder holds no record of the roots, and a font's name there can be a link leading + // out of them: the search asks the roots about each file before it opens one. + Some(roots) => cadcraft_fonts::shx::add_drawing_dir_guarded( + &dir, + std::sync::Arc::new(move |font| roots.check(font, crate::file_access::Access::Read).is_ok()), + ), } } Ok(ReadFile { drawing, binary_dxf: craft_dxf::is_binary(bytes), name: name.to_string(), path }) } -/// May the font search use `dir`? It holds no record of the automation roots, and a font's name -/// there can be a link leading out of them, so under the roots every font in the folder must stay -/// inside. -fn fonts_stay_inside_the_roots(dir: &std::path::Path) -> bool { - crate::file_access::current().is_none() - || std::fs::read_dir(dir).is_ok_and(|entries| { - entries - .flatten() - .all(|e| !e.file_name().to_string_lossy().to_ascii_lowercase().ends_with(".shx") || crate::file_access::check_read(e.path()).is_ok()) - }) -} - fn add_read(s: &mut Session, drawing: Drawing, binary_dxf: bool, name: &str, path: Option) -> usize { let notes = drawing.read_notes.clone(); let i = s.open_drawing(drawing, &file_name(name), path); diff --git a/crates/engine/src/cmd/file/template.rs b/crates/engine/src/cmd/file/template.rs index 386b898e43..e3f1148aeb 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -73,6 +73,7 @@ fn read_template(path: &str) -> Result { } #[cfg(not(target_arch = "wasm32"))] +/// The bytes of the template at `path`, once the automation roots allow reading it. fn read_bytes(path: &str) -> Result> { crate::file_access::check_read(path).map_err(|e| bad("new", e))?; crate::capped_read::read_capped(std::path::Path::new(path), super::MAX_DRAWING_BYTES).map_err(|e| bad("new", format!("template {path}: {e}"))) diff --git a/crates/engine/src/cmd/helpers.rs b/crates/engine/src/cmd/helpers.rs index ad9d5aaf7f..82bf54707a 100644 --- a/crates/engine/src/cmd/helpers.rs +++ b/crates/engine/src/cmd/helpers.rs @@ -115,6 +115,7 @@ pub fn support_text(cmd: &str, p: &serde_json::Value, path_key: &str, text_key: } #[cfg(not(target_arch = "wasm32"))] +/// The text of the support file at `path`, once the automation roots allow reading it, up to the size limit. fn read_support_file(cmd: &str, path: &str) -> crate::Result { use std::io::Read; crate::file_access::check_read(path).map_err(|e| super::bad(cmd, e))?; diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 1a3d46b4c4..f5d9cf6588 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -134,6 +134,7 @@ thread_local! { struct Restore(Option>); impl Drop for Restore { + /// Puts the roots it replaced back. fn drop(&mut self) { ROOTS.with(|r| *r.borrow_mut() = self.0.take()); } @@ -389,12 +390,14 @@ mod tests { impl std::ops::Deref for TestDir { type Target = Path; + /// The folder itself. fn deref(&self) -> &Path { &self.0 } } impl Drop for TestDir { + /// Removes the folder and all it holds; a failure here must not hide the test's own. fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } diff --git a/crates/fonts/src/shx/mod.rs b/crates/fonts/src/shx/mod.rs index 016fe98211..657c6e8296 100644 --- a/crates/fonts/src/shx/mod.rs +++ b/crates/fonts/src/shx/mod.rs @@ -41,8 +41,8 @@ use cadcraft_geom::Vec2; pub use compile::compile; pub use table::{ - FontProvider, add_drawing_dir, clear_registered, drawing_dirs, find, font_map, generation, installed, register, search_path, set_font_dirs, - set_font_map, set_provider, set_search_path, + FontProvider, OpenGuard, add_drawing_dir, add_drawing_dir_guarded, clear_registered, drawing_dirs, find, font_map, generation, installed, + register, search_path, set_font_dirs, set_font_map, set_provider, set_search_path, }; pub use text::ShxText; pub(crate) use text::{shape, width}; diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index efcca16b6c..19107ecb6b 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -23,6 +23,10 @@ pub trait FontProvider: Send + Sync { fn load(&self, file_name: &str) -> Option>; } +/// Decides whether the file at a path may be opened by the font search; asked of every candidate in +/// a folder, before anything opens it. +pub type OpenGuard = Arc bool + Send + Sync>; + /// Most fonts kept loaded, and their total bytes. const MAX_FONTS: usize = 128; const MAX_LOADED_BYTES: usize = 256 << 20; @@ -38,6 +42,8 @@ struct Table { loaded_bytes: usize, provider: Option>, drawing_dirs: Vec, + /// The guards of the drawing folders that have one. + drawing_guards: HashMap, font_dirs: Vec, search_path: Vec, map: Vec<(String, String)>, @@ -118,16 +124,39 @@ pub fn set_provider(provider: Option>) { /// Search the folder of a drawing being opened for the fonts its styles name (most recent /// first). pub fn add_drawing_dir(dir: &Path) { + add_dir(dir, None); +} + +/// Like [`add_drawing_dir`], with every file the search would open in `dir` put to `guard` first, +/// whatever its name and however it is found in the folder: a font the guard refuses is skipped. The +/// guard stays with the folder until the folder is added again. +pub fn add_drawing_dir_guarded(dir: &Path, guard: OpenGuard) { + add_dir(dir, Some(guard)); +} + +/// Remember `dir`, most recent first, with the guard it is searched under (none: unrestricted). +fn add_dir(dir: &Path, guard: Option) { if dir.as_os_str().is_empty() { return; } let mut t = table(); - if t.drawing_dirs.first().is_some_and(|d| d == dir) { + if guard.is_none() && t.drawing_dirs.first().is_some_and(|d| d == dir) && !t.drawing_guards.contains_key(dir) { return; } t.drawing_dirs.retain(|d| d != dir); t.drawing_dirs.insert(0, dir.to_path_buf()); t.drawing_dirs.truncate(MAX_DIRS); + match guard { + Some(g) => { + t.drawing_guards.insert(dir.to_path_buf(), g); + } + None => { + t.drawing_guards.remove(dir); + } + } + // A folder dropped from the list takes its guard with it. + let Table { drawing_dirs, drawing_guards, .. } = &mut *t; + drawing_guards.retain(|d, _| drawing_dirs.contains(d)); t.changed(); } @@ -206,7 +235,9 @@ pub fn find(name: &str) -> Option> { if let Some(r) = t.resolved.get(&k) { return r.clone(); } - let dirs: Vec = t.drawing_dirs.iter().chain(t.font_dirs.iter()).chain(t.search_path.iter()).cloned().collect(); + let drawing = t.drawing_dirs.iter().map(|d| (d.clone(), t.drawing_guards.get(d).cloned())); + let dirs: Vec<(PathBuf, Option)> = + drawing.chain(t.font_dirs.iter().chain(t.search_path.iter()).map(|d| (d.clone(), None))).collect(); (t.provider.clone(), dirs, t.generation) }; let font = provider @@ -266,21 +297,17 @@ pub fn installed() -> Vec { /// The file `name` (a lower-case key) in the first of `dirs` that has it, whatever the case of /// its name: lower-case, upper-case, else any other case found in the directory (`Simplex.shx` -/// on a case-sensitive file system). +/// on a case-sensitive file system). A folder's guard is asked about each candidate before anything +/// opens it, so a link is judged by where it leads. #[cfg(not(target_arch = "wasm32"))] -fn read_from(dirs: &[PathBuf], name: &str) -> Option> { - use std::io::Read as _; - let read = |file: &Path| -> Option> { - let meta = std::fs::metadata(file).ok()?; - if !meta.is_file() || meta.len() > MAX_FILE_BYTES as u64 { - return None; - } - let mut bytes = Vec::new(); - let limit = u64::try_from(MAX_FILE_BYTES).unwrap_or(u64::MAX).saturating_add(1); - std::fs::File::open(file).and_then(|f| f.take(limit).read_to_end(&mut bytes)).ok()?; - Some(bytes) - }; - for d in dirs { +fn read_from(dirs: &[(PathBuf, Option)], name: &str) -> Option> { + for (d, guard) in dirs { + let read = |file: &Path| -> Option> { + if guard.as_ref().is_some_and(|g| !g(file)) { + return None; + } + read_file(file) + }; if let Some(b) = [d.join(name), d.join(name.to_ascii_uppercase())].iter().find_map(|f| read(f)) { return Some(b); } @@ -297,7 +324,21 @@ fn read_from(dirs: &[PathBuf], name: &str) -> Option> { None } +/// The bytes of the SHX file at `file`, when it is a file of a sensible size. +#[cfg(not(target_arch = "wasm32"))] +fn read_file(file: &Path) -> Option> { + use std::io::Read as _; + let meta = std::fs::metadata(file).ok()?; + if !meta.is_file() || meta.len() > MAX_FILE_BYTES as u64 { + return None; + } + let mut bytes = Vec::new(); + let limit = u64::try_from(MAX_FILE_BYTES).unwrap_or(u64::MAX).saturating_add(1); + std::fs::File::open(file).and_then(|f| f.take(limit).read_to_end(&mut bytes)).ok()?; + Some(bytes) +} + #[cfg(target_arch = "wasm32")] -fn read_from(_dirs: &[PathBuf], _name: &str) -> Option> { +fn read_from(_dirs: &[(PathBuf, Option)], _name: &str) -> Option> { None } diff --git a/crates/fonts/tests/shx_guard.rs b/crates/fonts/tests/shx_guard.rs new file mode 100644 index 0000000000..aeaf5a478e --- /dev/null +++ b/crates/fonts/tests/shx_guard.rs @@ -0,0 +1,54 @@ +//! A guarded drawing folder: the font search asks the guard about every file it would open there, +//! before opening it (the automation roots use this to keep a font link from leading out of them). +// Integration tests: unwrapping on failure is fine here, unlike in shipped code (AGENTS.md). +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use cadcraft_fonts::shx; + +const FONT: &str = "*0,4,guard\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n"; + +/// A new folder of this test's own. +fn fresh_dir() -> PathBuf { + let dir = std::env::temp_dir().join(format!("cadcraft-shx-guard-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Every candidate the search opens in a guarded folder goes to the guard first, whatever its name +/// or how the search finds it, and a font the guard refuses is skipped while the others are used. +#[test] +fn every_file_the_search_opens_goes_to_the_guard_first() { + let bytes = shx::compile(FONT).unwrap(); + let dir = fresh_dir(); + std::fs::write(dir.join("cadcraft-guard-ok.shx"), &bytes).unwrap(); + std::fs::write(dir.join("cadcraft-guard-bad.shx"), &bytes).unwrap(); + // Found only by looking through the folder, as a link under another spelling would be. + std::fs::write(dir.join("CadCraft-Guard-Mixed.SHX"), &bytes).unwrap(); + std::fs::write(dir.join("CadCraft-Guard-Badmixed.SHX"), &bytes).unwrap(); + let asked: Arc>> = Arc::default(); + let log = asked.clone(); + shx::add_drawing_dir_guarded( + &dir, + Arc::new(move |file: &Path| { + log.lock().unwrap().push(file.to_path_buf()); + !file.to_string_lossy().to_ascii_lowercase().contains("bad") + }), + ); + assert!(shx::find("cadcraft-guard-ok.shx").is_some()); + assert!(shx::find("cadcraft-guard-mixed.shx").is_some(), "a name found by looking through the folder"); + assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "a font the guard refuses is skipped"); + assert!(shx::find("cadcraft-guard-badmixed.shx").is_none(), "also one found by looking through the folder"); + let asked = asked.lock().unwrap(); + for file in + ["cadcraft-guard-ok.shx", "CADCRAFT-GUARD-OK.SHX", "cadcraft-guard-bad.shx", "CadCraft-Guard-Mixed.SHX", "CadCraft-Guard-Badmixed.SHX"] + { + assert!(asked.contains(&dir.join(file)), "the guard was asked about {file}: {asked:?}"); + } + // The guard goes with the folder: added again without one, the folder is searched freely. + shx::add_drawing_dir(&dir); + assert!(shx::find("cadcraft-guard-bad.shx").is_some()); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 842b96e830..cd0c869453 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -300,6 +300,7 @@ impl Backend for Remote { fn has_ui(&self) -> bool { true } + /// What this backend talks to, for messages. fn describe(&self) -> String { format!("connected to CADCraft at {}", self.addr) } diff --git a/docs/mcp.md b/docs/mcp.md index 61b33c2f66..f18e67ce41 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -67,8 +67,8 @@ configuration works across the suite) keep the agent to the folders you give it: `LPT¹`…) are refused too. - A path you write must also stand under the write root: a link outside it pointing in is refused, because a drawing's `.bak` goes beside the link and a delete removes the link. -- A refused path is an ordinary tool error with `isError: true` that the agent can read and - correct, for example `automation path rejected: outside the write root +- A refused path in a tool other than `command_line` is an ordinary tool error with `isError: true` + that the agent can read and correct, for example `automation path rejected: outside the write root /work/project/out: /etc/x.png`, `automation path rejected: outside the read root (or the write root): /etc/x.png`, `automation path rejected: the write root itself cannot be written: /work/project/out`, `automation path rejected: UNC paths are refused unless a root is on the @@ -79,8 +79,9 @@ configuration works across the suite) keep the agent to the folders you give it: - A command runs under the roots only if it is classified (`crates/engine/src/file_access/commands.rs`): one nobody classified is refused, whatever it does. `drawingrecovery` is refused, and SAVEFILEPATH can't be changed, because both work on the server's autosave folder. -- SHX fonts beside an opened drawing are searched only if every `.shx` in that folder stays inside - the roots: one link leading out and the folder is skipped. +- SHX fonts beside an opened drawing are searched, and each file the search would open there is + checked against the roots first, whatever its name: a font that is a link leading out of the + roots is skipped, and the rest of the folder is still used. - The server itself still reads the system's fonts, from the system font folders and `CADCRAFT_SHXPATH`. Their paths come from the server's setup, never from the agent, but a font file named by a drawing can decide which of them is read. From d4c4c799826a6c763d08c910817dcf8c5aaffcce Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:00:15 +0530 Subject: [PATCH 12/27] Probe only the places the roots allow when matching a name's case, and fix the guard test CodeRabbit's CLI found that a name corrected to another case (Alias for alias) was looked inside before the roots judged it, and that a case match the roots refused ended the search before the next candidate. Each corrected name is now checked before it is probed, and each match before it is taken. The guard test no longer expects a candidate that is never opened once an earlier one read, and the MCP test helper refuses an error reply instead of reading it as a success. --- apps/cadcraft-cli/tests/mcp_roots.rs | 1 + crates/engine/src/cmd/blocks/xref/load.rs | 40 ++++++++++++++++++++++- crates/fonts/tests/shx_guard.rs | 9 ++--- 3 files changed, 45 insertions(+), 5 deletions(-) diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs index f3c21904af..b70931c90d 100644 --- a/apps/cadcraft-cli/tests/mcp_roots.rs +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -102,6 +102,7 @@ fn run_env(args: &[&str], calls: &[(&str, Value)], env: &[(&str, &str)]) -> (Out .map(|(i, (name, arguments))| { let id = (i + 2) as u64; let reply = replies.iter().find(|v| v["id"] == id).unwrap_or_else(|| panic!("no reply to {name} {arguments}: {replies:?}")); + assert!(reply.get("error").is_none() && reply["result"].is_object(), "{name} {arguments} got an error reply, not a tool result: {reply}"); let result = &reply["result"]; Tool { error: result["isError"] == true, text: result["content"][0]["text"].as_str().unwrap_or_default().to_string() } }) diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index 788877e2b8..ff30c103af 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -221,7 +221,7 @@ pub(crate) fn find(path: &str, host: Option<&Path>, chosen: bool) -> Result = files.into_iter().filter(allowed).collect(); let outside = files.len() < looked_for; #[cfg(not(target_arch = "wasm32"))] - let found = files.iter().find(|p| p.is_file()).cloned().or_else(|| files.iter().find_map(|p| case_insensitive(p))).filter(allowed); + let found = files.iter().find(|p| p.is_file()).cloned().or_else(|| files.iter().find_map(|p| case_insensitive(p).filter(allowed))); #[cfg(target_arch = "wasm32")] let found: Option = None; found.ok_or(if outside { Missing::OutsideRoots } else { refused.map_or(Missing::NotFound, Missing::Refused) }) @@ -238,6 +238,11 @@ const MAX_CASE_SCAN: usize = 10_000; #[cfg(not(target_arch = "wasm32"))] fn case_insensitive(p: &Path) -> Option { use std::path::Component; + // Under the automation roots a place is probed only when the roots allow it, or when it lies on + // the way to `p` as it was spelled (which was checked): a name corrected to another case could be + // a link leading out, and looking inside it would look outside the roots. + let mut corrected = false; + let probe = |q: &Path, corrected: bool| (!corrected && p.starts_with(q)) || crate::file_access::check_read(q).is_ok(); let mut out = PathBuf::new(); for c in p.components() { let Component::Normal(name) = c else { @@ -245,6 +250,9 @@ fn case_insensitive(p: &Path) -> Option { continue; }; let exact = out.join(name); + if !probe(&exact, corrected) { + return None; + } if exact.exists() { out = exact; continue; @@ -260,6 +268,10 @@ fn case_insensitive(p: &Path) -> Option { return None; } out.push(hit.file_name()); + corrected = true; + if !probe(&out, corrected) { + return None; + } } out.is_file().then_some(out) } @@ -613,6 +625,32 @@ mod tests { assert_eq!(find("", Some(&host), false), Err(Missing::NotFound)); } + #[cfg(unix)] + #[test] + fn a_name_corrected_to_a_link_out_of_the_roots_is_not_looked_inside() { + use crate::file_access::{AutomationRoots, confine}; + let base = std::env::temp_dir().join(format!("cc-xref-case-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["in/sub", "outside"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + std::fs::write(base.join("outside/target.dxf"), "x").unwrap(); + std::fs::write(base.join("in/Mixed.dxf"), "x").unwrap(); + std::os::unix::fs::symlink(base.join("outside"), base.join("in/Alias")).unwrap(); + std::os::unix::fs::symlink(base.join("outside/target.dxf"), base.join("in/sub/Mixed.dxf")).unwrap(); + let roots = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); + confine(Some(&roots), || { + // `alias` isn't there but `Alias` is, a link out: the probe stops before looking in it. + assert_eq!(case_insensitive(&base.join("in/alias/target.dxf")), None); + // A match that leaves the roots doesn't end the search: the next candidate is tried. + let host = base.join("in/host.dxf"); + let found = find("sub/mixed.dxf", Some(&host), true).unwrap(); + assert_eq!(found, base.join("in/Mixed.dxf")); + }); + assert_eq!(case_insensitive(&base.join("in/alias/target.dxf")), Some(base.join("in/Alias/target.dxf")), "without roots the link is followed"); + std::fs::remove_dir_all(&base).unwrap(); + } + #[test] fn prefixes_ignore_case() { assert!(has_prefix("SITE|Walls", "site|")); diff --git a/crates/fonts/tests/shx_guard.rs b/crates/fonts/tests/shx_guard.rs index aeaf5a478e..9196cd018a 100644 --- a/crates/fonts/tests/shx_guard.rs +++ b/crates/fonts/tests/shx_guard.rs @@ -42,10 +42,11 @@ fn every_file_the_search_opens_goes_to_the_guard_first() { assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "a font the guard refuses is skipped"); assert!(shx::find("cadcraft-guard-badmixed.shx").is_none(), "also one found by looking through the folder"); let asked = asked.lock().unwrap(); - for file in - ["cadcraft-guard-ok.shx", "CADCRAFT-GUARD-OK.SHX", "cadcraft-guard-bad.shx", "CadCraft-Guard-Mixed.SHX", "CadCraft-Guard-Badmixed.SHX"] - { - assert!(asked.contains(&dir.join(file)), "the guard was asked about {file}: {asked:?}"); + // The guard saw each font's file under the spelling the search tried (a file system that + // ignores case answers the first one, so only the letters are compared). + for file in ["cadcraft-guard-ok.shx", "cadcraft-guard-bad.shx", "cadcraft-guard-mixed.shx", "cadcraft-guard-badmixed.shx"] { + let want = dir.join(file).to_string_lossy().to_ascii_lowercase(); + assert!(asked.iter().any(|a| a.to_string_lossy().to_ascii_lowercase() == want), "the guard was asked about {file}: {asked:?}"); } // The guard goes with the folder: added again without one, the folder is searched freely. shx::add_drawing_dir(&dir); From 99118a2bda954525b9dc9de67bd95553bae82675 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:01:45 +0530 Subject: [PATCH 13/27] Document the font guard's remaining functions and the xref case test --- crates/engine/src/cmd/blocks/xref/load.rs | 2 ++ crates/fonts/src/shx/table.rs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index ff30c103af..cc960cf85f 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -625,6 +625,8 @@ mod tests { assert_eq!(find("", Some(&host), false), Err(Missing::NotFound)); } + /// A name corrected to another case is checked against the roots before it is looked inside, and a + /// match they refuse leaves the other candidates to be tried. #[cfg(unix)] #[test] fn a_name_corrected_to_a_link_out_of_the_roots_is_not_looked_inside() { diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index 19107ecb6b..4fc55910d1 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -20,6 +20,7 @@ use super::{ShxError, ShxFont}; /// app's own font folder). Called with the normalised file name (`romans.shx`); returns the /// file's bytes. Called without the font table's lock held. pub trait FontProvider: Send + Sync { + /// The bytes of the font file `file_name`, or `None` when this provider has none by that name. fn load(&self, file_name: &str) -> Option>; } @@ -338,6 +339,7 @@ fn read_file(file: &Path) -> Option> { Some(bytes) } +/// On the web there are no folders to search. #[cfg(target_arch = "wasm32")] fn read_from(_dirs: &[(PathBuf, Option)], _name: &str) -> Option> { None From 99f442d40e9346b7a64fa610429c6dedec808ebd Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:51:58 +0530 Subject: [PATCH 14/27] Skip the case-correction test where the file system ignores case --- crates/engine/src/cmd/blocks/xref/load.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index cc960cf85f..3437cdd0a7 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -640,6 +640,12 @@ mod tests { std::fs::write(base.join("in/Mixed.dxf"), "x").unwrap(); std::os::unix::fs::symlink(base.join("outside"), base.join("in/Alias")).unwrap(); std::os::unix::fs::symlink(base.join("outside/target.dxf"), base.join("in/sub/Mixed.dxf")).unwrap(); + if base.join("in/alias").exists() { + // A case-insensitive file system never needs a name corrected: nothing to test. + eprintln!("skipped: this file system ignores case"); + std::fs::remove_dir_all(&base).unwrap(); + return; + } let roots = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); confine(Some(&roots), || { // `alias` isn't there but `Alias` is, a link out: the probe stops before looking in it. From 4efecc2f0e03b49e72f6b169229a4635b6a404d9 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:03:04 +0530 Subject: [PATCH 15/27] Keep every owner's font guard for a folder and require all of them The font table is shared by the process, so a folder added without a guard (or with another owner's) dropped the guard of a confined session and its font links were opened unchecked. A folder now keeps the guard of each owner that gave one, and a font is opened only when all of them allow it. --- crates/engine/src/cmd/file.rs | 9 +++--- crates/fonts/src/shx/table.rs | 54 +++++++++++++++++---------------- crates/fonts/tests/shx_guard.rs | 20 ++++++++++-- 3 files changed, 50 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index c5a025bb54..d2dbd581fa 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -346,10 +346,11 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result cadcraft_fonts::shx::add_drawing_dir(&dir), // The folder holds no record of the roots, and a font's name there can be a link leading // out of them: the search asks the roots about each file before it opens one. - Some(roots) => cadcraft_fonts::shx::add_drawing_dir_guarded( - &dir, - std::sync::Arc::new(move |font| roots.check(font, crate::file_access::Access::Read).is_ok()), - ), + Some(roots) => { + let owner = format!("{:?}|{:?}", roots.read_root(), roots.write_root()); + let guard = std::sync::Arc::new(move |font: &std::path::Path| roots.check(font, crate::file_access::Access::Read).is_ok()); + cadcraft_fonts::shx::add_drawing_dir_guarded(&dir, &owner, guard); + } } } Ok(ReadFile { drawing, binary_dxf: craft_dxf::is_binary(bytes), name: name.to_string(), path }) diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index 4fc55910d1..0542d59744 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -43,8 +43,8 @@ struct Table { loaded_bytes: usize, provider: Option>, drawing_dirs: Vec, - /// The guards of the drawing folders that have one. - drawing_guards: HashMap, + /// The guards of the drawing folders that have any, by the owner that gave each one. + drawing_guards: HashMap>, font_dirs: Vec, search_path: Vec, map: Vec<(String, String)>, @@ -129,33 +129,34 @@ pub fn add_drawing_dir(dir: &Path) { } /// Like [`add_drawing_dir`], with every file the search would open in `dir` put to `guard` first, -/// whatever its name and however it is found in the folder: a font the guard refuses is skipped. The -/// guard stays with the folder until the folder is added again. -pub fn add_drawing_dir_guarded(dir: &Path, guard: OpenGuard) { - add_dir(dir, Some(guard)); +/// whatever its name and however it is found in the folder: a font the guard refuses is skipped. +/// +/// The table is shared by the whole process, so a folder keeps the guard of every `owner` that gave +/// one (an owner giving it again replaces its own) and a font is opened only when all of them allow +/// it. Adding the folder without a guard never removes one. Fonts found are kept for every caller, +/// so owners with different rules shouldn't share a process. +pub fn add_drawing_dir_guarded(dir: &Path, owner: &str, guard: OpenGuard) { + add_dir(dir, Some((owner, guard))); } -/// Remember `dir`, most recent first, with the guard it is searched under (none: unrestricted). -fn add_dir(dir: &Path, guard: Option) { +/// Remember `dir`, most recent first, with the guard it is searched under, if any. +fn add_dir(dir: &Path, guard: Option<(&str, OpenGuard)>) { if dir.as_os_str().is_empty() { return; } let mut t = table(); - if guard.is_none() && t.drawing_dirs.first().is_some_and(|d| d == dir) && !t.drawing_guards.contains_key(dir) { + if guard.is_none() && t.drawing_dirs.first().is_some_and(|d| d == dir) { return; } t.drawing_dirs.retain(|d| d != dir); t.drawing_dirs.insert(0, dir.to_path_buf()); t.drawing_dirs.truncate(MAX_DIRS); - match guard { - Some(g) => { - t.drawing_guards.insert(dir.to_path_buf(), g); - } - None => { - t.drawing_guards.remove(dir); - } + if let Some((owner, guard)) = guard { + let guards = t.drawing_guards.entry(dir.to_path_buf()).or_default(); + guards.retain(|(o, _)| o != owner); + guards.push((owner.to_string(), guard)); } - // A folder dropped from the list takes its guard with it. + // A folder dropped from the list takes its guards with it. let Table { drawing_dirs, drawing_guards, .. } = &mut *t; drawing_guards.retain(|d, _| drawing_dirs.contains(d)); t.changed(); @@ -236,9 +237,10 @@ pub fn find(name: &str) -> Option> { if let Some(r) = t.resolved.get(&k) { return r.clone(); } - let drawing = t.drawing_dirs.iter().map(|d| (d.clone(), t.drawing_guards.get(d).cloned())); - let dirs: Vec<(PathBuf, Option)> = - drawing.chain(t.font_dirs.iter().chain(t.search_path.iter()).map(|d| (d.clone(), None))).collect(); + let guards = |d: &PathBuf| t.drawing_guards.get(d).map(|g| g.iter().map(|(_, g)| g.clone()).collect()).unwrap_or_default(); + let drawing = t.drawing_dirs.iter().map(|d| (d.clone(), guards(d))); + let dirs: Vec<(PathBuf, Vec)> = + drawing.chain(t.font_dirs.iter().chain(t.search_path.iter()).map(|d| (d.clone(), Vec::new()))).collect(); (t.provider.clone(), dirs, t.generation) }; let font = provider @@ -298,13 +300,13 @@ pub fn installed() -> Vec { /// The file `name` (a lower-case key) in the first of `dirs` that has it, whatever the case of /// its name: lower-case, upper-case, else any other case found in the directory (`Simplex.shx` -/// on a case-sensitive file system). A folder's guard is asked about each candidate before anything -/// opens it, so a link is judged by where it leads. +/// on a case-sensitive file system). Each of a folder's guards is asked about each candidate before +/// anything opens it, so a link is judged by where it leads. #[cfg(not(target_arch = "wasm32"))] -fn read_from(dirs: &[(PathBuf, Option)], name: &str) -> Option> { - for (d, guard) in dirs { +fn read_from(dirs: &[(PathBuf, Vec)], name: &str) -> Option> { + for (d, guards) in dirs { let read = |file: &Path| -> Option> { - if guard.as_ref().is_some_and(|g| !g(file)) { + if !guards.iter().all(|g| g(file)) { return None; } read_file(file) @@ -341,6 +343,6 @@ fn read_file(file: &Path) -> Option> { /// On the web there are no folders to search. #[cfg(target_arch = "wasm32")] -fn read_from(_dirs: &[(PathBuf, Option)], _name: &str) -> Option> { +fn read_from(_dirs: &[(PathBuf, Vec)], _name: &str) -> Option> { None } diff --git a/crates/fonts/tests/shx_guard.rs b/crates/fonts/tests/shx_guard.rs index 9196cd018a..5b66a1857b 100644 --- a/crates/fonts/tests/shx_guard.rs +++ b/crates/fonts/tests/shx_guard.rs @@ -17,6 +17,11 @@ fn fresh_dir() -> PathBuf { dir } +/// The lower-case file name of `file`, so a guard never reads the test folder's own name. +fn name(file: &Path) -> String { + file.file_name().map(|n| n.to_string_lossy().to_ascii_lowercase()).unwrap_or_default() +} + /// Every candidate the search opens in a guarded folder goes to the guard first, whatever its name /// or how the search finds it, and a font the guard refuses is skipped while the others are used. #[test] @@ -32,9 +37,10 @@ fn every_file_the_search_opens_goes_to_the_guard_first() { let log = asked.clone(); shx::add_drawing_dir_guarded( &dir, + "first", Arc::new(move |file: &Path| { log.lock().unwrap().push(file.to_path_buf()); - !file.to_string_lossy().to_ascii_lowercase().contains("bad") + !name(file).contains("bad") }), ); assert!(shx::find("cadcraft-guard-ok.shx").is_some()); @@ -48,8 +54,16 @@ fn every_file_the_search_opens_goes_to_the_guard_first() { let want = dir.join(file).to_string_lossy().to_ascii_lowercase(); assert!(asked.iter().any(|a| a.to_string_lossy().to_ascii_lowercase() == want), "the guard was asked about {file}: {asked:?}"); } - // The guard goes with the folder: added again without one, the folder is searched freely. + // The folder added again without a guard (another session in the process) keeps its guard. shx::add_drawing_dir(&dir); - assert!(shx::find("cadcraft-guard-bad.shx").is_some()); + assert!(shx::find("cadcraft-guard-bad.shx").is_none()); + // Another owner's guard is required as well: a font is opened only when every owner allows it. + shx::add_drawing_dir_guarded(&dir, "second", Arc::new(|file: &Path| !name(file).contains("ok"))); + assert!(shx::find("cadcraft-guard-ok.shx").is_none(), "refused by the second owner"); + assert!(shx::find("cadcraft-guard-mixed.shx").is_some(), "allowed by both"); + // An owner giving its guard again replaces its own, and the other's stays. + shx::add_drawing_dir_guarded(&dir, "second", Arc::new(|_: &Path| true)); + assert!(shx::find("cadcraft-guard-ok.shx").is_some()); + assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "the first owner's guard still holds"); std::fs::remove_dir_all(&dir).unwrap(); } From 8cfb9cfa8c8abf541b2440a9aa5c314c2b74b7d2 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:54:46 +0530 Subject: [PATCH 16/27] Hold a font folder named twice to its guards, and fix the guard test's lock and the walk test's status checks A drawing's folder that is also a font folder or on the search path was searched again without its guards, so a rejected link was opened on the second pass. Guards now follow the folder however the search reaches it. The guard test held its lock across a later search and would have deadlocked, and the font walk tests ignored an error reply from open or render. --- apps/cadcraft-cli/tests/mcp_roots_walk.rs | 22 +++++++++++++------- crates/fonts/src/shx/table.rs | 25 +++++++++++++++++------ crates/fonts/tests/shx_guard.rs | 6 ++++++ 3 files changed, 40 insertions(+), 13 deletions(-) diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index f4c0032f78..6b591b3b6d 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -94,6 +94,14 @@ impl Server { Some(reply["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string()) } + /// Like [`Self::tool`] for a call that must work: an error reply, or a result flagged as an + /// error, fails the test. + fn tool_ok(&mut self, name: &str, arguments: Value) -> String { + let reply = self.request("tools/call", json!({"name": name, "arguments": arguments})).expect("the server answered"); + assert!(reply.get("error").is_none() && reply["result"]["isError"] != true, "{name} should have worked: {reply}"); + reply["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string() + } + /// Run an engine command through the `execute` tool. fn execute(&mut self, command: &str, params: Value) -> Option { self.tool("execute", json!({"command": command, "params": params})) @@ -584,7 +592,7 @@ fn a_drawing_cannot_reach_files_it_names_outside_the_roots() { let opened = server.tool("open", json!({"path": s(&host)})).unwrap(); let images = server.execute("image", json!({})).unwrap(); let xrefs = server.execute("xref", json!({})).unwrap(); - server.tool("render", json!({})).unwrap(); + server.tool_ok("render", json!({})); let touched = f.touched(); assert!(touched.is_empty(), "{touched:?}\nopen: {opened}\nimage: {images}\nxref: {xrefs}"); assert!(images.contains("canary.png") && !images.contains("\"Loaded\""), "the image stays unloaded: {images}"); @@ -615,8 +623,8 @@ fn a_font_linked_beside_a_drawing_is_not_followed_out() { f.reset(); std::fs::write(f.outside.join("walkfont.shx"), b"AutoCAD-86 shapes 1.0").unwrap(); f.watch(); - server.tool("open", json!({"path": s(&host)})).unwrap(); - server.tool("render", json!({})).unwrap(); + server.tool_ok("open", json!({"path": s(&host)})); + server.tool_ok("render", json!({})); let touched = f.touched(); assert!(touched.is_empty(), "{touched:?}"); } @@ -681,8 +689,8 @@ fn a_font_beside_a_drawing_inside_the_roots_is_used() { let before = std::fs::metadata(&font).unwrap().accessed().unwrap(); let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))]; let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config")); - server.tool("open", json!({"path": s(&host)})).unwrap(); - server.tool("render", json!({})).unwrap(); + server.tool_ok("open", json!({"path": s(&host)})); + server.tool_ok("render", json!({})); if f.sees_reads { assert_ne!(std::fs::metadata(&font).unwrap().accessed().unwrap(), before, "the font was read"); } @@ -714,8 +722,8 @@ fn a_font_link_leading_out_does_not_cost_the_fonts_beside_it() { std::fs::write(f.outside.join("walkbad.shx"), b"AutoCAD-86 shapes 1.0").unwrap(); std::os::unix::fs::symlink(f.outside.join("walkbad.shx"), f.base.join("in/walkbad.shx")).unwrap(); f.watch(); - server.tool("open", json!({"path": s(&host)})).unwrap(); - server.tool("render", json!({})).unwrap(); + server.tool_ok("open", json!({"path": s(&host)})); + server.tool_ok("render", json!({})); let touched = f.touched(); assert!(touched.is_empty(), "{touched:?}"); if f.sees_reads { diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index 0542d59744..f809b88a21 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -225,7 +225,7 @@ pub fn generation() -> u64 { /// The SHX font file a style or linetype names, if CADCraft can find and read it. pub fn find(name: &str) -> Option> { let mut k = key(name)?; - let (provider, dirs, generation) = { + let (provider, folders, guarded, generation) = { let t = table(); // The font map renames once (a map can't loop). if let Some(to) = t.map.iter().find(|(from, _)| *from == k).and_then(|(_, to)| key(to)) { @@ -237,12 +237,20 @@ pub fn find(name: &str) -> Option> { if let Some(r) = t.resolved.get(&k) { return r.clone(); } - let guards = |d: &PathBuf| t.drawing_guards.get(d).map(|g| g.iter().map(|(_, g)| g.clone()).collect()).unwrap_or_default(); - let drawing = t.drawing_dirs.iter().map(|d| (d.clone(), guards(d))); - let dirs: Vec<(PathBuf, Vec)> = - drawing.chain(t.font_dirs.iter().chain(t.search_path.iter()).map(|d| (d.clone(), Vec::new()))).collect(); - (t.provider.clone(), dirs, t.generation) + let folders: Vec = t.drawing_dirs.iter().chain(t.font_dirs.iter()).chain(t.search_path.iter()).cloned().collect(); + let guarded: Vec<(PathBuf, Vec)> = + t.drawing_guards.iter().map(|(d, g)| (d.clone(), g.iter().map(|(_, g)| g.clone()).collect())).collect(); + (t.provider.clone(), folders, guarded, t.generation) }; + // A guard belongs to the folder, however the search reaches it: a font folder or the search path + // naming the same folder as a drawing's is held to the same guards. + let dirs: Vec<(PathBuf, Vec)> = folders + .into_iter() + .map(|d| { + let guards = guarded.iter().filter(|(g, _)| same_folder(g, &d)).flat_map(|(_, g)| g.iter().cloned()).collect(); + (d, guards) + }) + .collect(); let font = provider .and_then(|p| p.load(&k)) .or_else(|| read_from(&dirs, &k)) @@ -268,6 +276,11 @@ pub fn find(name: &str) -> Option> { font } +/// Do `a` and `b` name the same folder, as spelled or once the file system has resolved them? +fn same_folder(a: &Path, b: &Path) -> bool { + a == b || matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b) +} + /// Most directory entries looked at for a font file whose name differs only in case. #[cfg(not(target_arch = "wasm32"))] const MAX_DIR_ENTRIES: usize = 10_000; diff --git a/crates/fonts/tests/shx_guard.rs b/crates/fonts/tests/shx_guard.rs index 5b66a1857b..1c1b5fa3b9 100644 --- a/crates/fonts/tests/shx_guard.rs +++ b/crates/fonts/tests/shx_guard.rs @@ -54,6 +54,7 @@ fn every_file_the_search_opens_goes_to_the_guard_first() { let want = dir.join(file).to_string_lossy().to_ascii_lowercase(); assert!(asked.iter().any(|a| a.to_string_lossy().to_ascii_lowercase() == want), "the guard was asked about {file}: {asked:?}"); } + drop(asked); // The folder added again without a guard (another session in the process) keeps its guard. shx::add_drawing_dir(&dir); assert!(shx::find("cadcraft-guard-bad.shx").is_none()); @@ -65,5 +66,10 @@ fn every_file_the_search_opens_goes_to_the_guard_first() { shx::add_drawing_dir_guarded(&dir, "second", Arc::new(|_: &Path| true)); assert!(shx::find("cadcraft-guard-ok.shx").is_some()); assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "the first owner's guard still holds"); + // The same folder named as a font folder or on the search path is held to its guards too. + shx::set_font_dirs(vec![dir.clone()]); + shx::set_search_path(&dir.to_string_lossy()); + assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "a font folder or the search path doesn't lift the guard"); + assert!(shx::find("cadcraft-guard-ok.shx").is_some()); std::fs::remove_dir_all(&dir).unwrap(); } From d4c1ae0e23feaef6504b8b292b11761fc1b2d155 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:15:22 +0530 Subject: [PATCH 17/27] Keep a folder's font guards after it drops off the list of drawing folders A guarded folder that is also a font folder or on the search path lost its guards once 32 other folders had been opened, and the second list then opened a rejected link. Guards now outlive the list, bounded by a fail-closed cap, with a test that evicts the folder. --- crates/fonts/src/shx/table.rs | 13 +++++++++---- crates/fonts/tests/shx_guard.rs | 8 ++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index f809b88a21..dbeab77051 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -33,6 +33,8 @@ const MAX_FONTS: usize = 128; const MAX_LOADED_BYTES: usize = 256 << 20; /// Most drawing folders and search path entries remembered. const MAX_DIRS: usize = 32; +/// Most folders whose guards are kept. +const MAX_GUARDED_DIRS: usize = 1024; /// Most font map entries. const MAX_MAP: usize = 1024; @@ -139,7 +141,8 @@ pub fn add_drawing_dir_guarded(dir: &Path, owner: &str, guard: OpenGuard) { add_dir(dir, Some((owner, guard))); } -/// Remember `dir`, most recent first, with the guard it is searched under, if any. +/// Remember `dir`, most recent first, with the guard it is searched under, if any. The folder's +/// guards are kept after it drops off the list of drawing folders. fn add_dir(dir: &Path, guard: Option<(&str, OpenGuard)>) { if dir.as_os_str().is_empty() { return; @@ -148,6 +151,11 @@ fn add_dir(dir: &Path, guard: Option<(&str, OpenGuard)>) { if guard.is_none() && t.drawing_dirs.first().is_some_and(|d| d == dir) { return; } + // Guards outlive the drawing list: a folder dropped from it can still be reached as a font + // folder or on the search path. When there is no room for another, the folder isn't searched. + if guard.is_some() && !t.drawing_guards.contains_key(dir) && t.drawing_guards.len() >= MAX_GUARDED_DIRS { + return; + } t.drawing_dirs.retain(|d| d != dir); t.drawing_dirs.insert(0, dir.to_path_buf()); t.drawing_dirs.truncate(MAX_DIRS); @@ -156,9 +164,6 @@ fn add_dir(dir: &Path, guard: Option<(&str, OpenGuard)>) { guards.retain(|(o, _)| o != owner); guards.push((owner.to_string(), guard)); } - // A folder dropped from the list takes its guards with it. - let Table { drawing_dirs, drawing_guards, .. } = &mut *t; - drawing_guards.retain(|d, _| drawing_dirs.contains(d)); t.changed(); } diff --git a/crates/fonts/tests/shx_guard.rs b/crates/fonts/tests/shx_guard.rs index 1c1b5fa3b9..11f89dc930 100644 --- a/crates/fonts/tests/shx_guard.rs +++ b/crates/fonts/tests/shx_guard.rs @@ -71,5 +71,13 @@ fn every_file_the_search_opens_goes_to_the_guard_first() { shx::set_search_path(&dir.to_string_lossy()); assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "a font folder or the search path doesn't lift the guard"); assert!(shx::find("cadcraft-guard-ok.shx").is_some()); + // The folder falling off the list of drawing folders (the list is short) keeps its guards while a + // font folder or the search path still reaches it. + for n in 0..40 { + shx::add_drawing_dir(&dir.join(format!("other-{n}"))); + } + assert!(!shx::drawing_dirs().contains(&dir)); + assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "the outside font stays rejected after the eviction"); + assert!(shx::find("cadcraft-guard-ok.shx").is_some()); std::fs::remove_dir_all(&dir).unwrap(); } From 9cea2f780bd18260e70cbdf8b7432a1f30a2373a Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:28:28 +0530 Subject: [PATCH 18/27] Keep a refusal found by case correction, stat the .bak name without following it, and keep guards past the limit CodeRabbit's CLI found three more: a case-corrected match the roots refuse was reported as a missing file instead of a refusal; the .bak name was looked at through a link that could lead out of the roots (or to another computer); and a folder past the number of guarded folders kept was left unguarded where a font folder or the search path reached it, so its guards now apply to every folder searched. --- crates/engine/src/cmd/blocks/xref/load.rs | 18 +++++++++++- crates/engine/src/cmd/file.rs | 18 +++++++++++- crates/fonts/src/shx/table.rs | 19 +++++++------ crates/fonts/tests/shx_guard_overflow.rs | 34 +++++++++++++++++++++++ 4 files changed, 79 insertions(+), 10 deletions(-) create mode 100644 crates/fonts/tests/shx_guard_overflow.rs diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index 3437cdd0a7..8b1da3a499 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -220,8 +220,20 @@ pub(crate) fn find(path: &str, host: Option<&Path>, chosen: bool) -> Result = files.into_iter().filter(allowed).collect(); let outside = files.len() < looked_for; + // A match found by ignoring case that the roots refuse counts as outside them too. #[cfg(not(target_arch = "wasm32"))] - let found = files.iter().find(|p| p.is_file()).cloned().or_else(|| files.iter().find_map(|p| case_insensitive(p).filter(allowed))); + let mut refused_match = false; + #[cfg(not(target_arch = "wasm32"))] + let found = files.iter().find(|p| p.is_file()).cloned().or_else(|| { + files.iter().find_map(|p| { + let c = case_insensitive(p)?; + let ok = allowed(&c); + refused_match |= !ok; + ok.then_some(c) + }) + }); + #[cfg(not(target_arch = "wasm32"))] + let outside = outside || refused_match; #[cfg(target_arch = "wasm32")] let found: Option = None; found.ok_or(if outside { Missing::OutsideRoots } else { refused.map_or(Missing::NotFound, Missing::Refused) }) @@ -654,6 +666,10 @@ mod tests { let host = base.join("in/host.dxf"); let found = find("sub/mixed.dxf", Some(&host), true).unwrap(); assert_eq!(found, base.join("in/Mixed.dxf")); + // With no other candidate it is still a refusal by the roots, not a missing file. + std::fs::create_dir_all(base.join("in/lone")).unwrap(); + std::os::unix::fs::symlink(base.join("outside/target.dxf"), base.join("in/lone/Only.dxf")).unwrap(); + assert_eq!(find("lone/only.dxf", Some(&host), true), Err(Missing::OutsideRoots)); }); assert_eq!(case_insensitive(&base.join("in/alias/target.dxf")), Some(base.join("in/Alias/target.dxf")), "without roots the link is followed"); std::fs::remove_dir_all(&base).unwrap(); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index d2dbd581fa..e75322351b 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -688,7 +688,9 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> { }; let (head, tail, len) = ends(&mut src)?; let bak = backup_path(path); - if !backup_replaced(&head, &tail, len, bak.exists()) { + // Whether the .bak name is taken is asked without following a link there: a link leading out of + // the roots (or to another computer) isn't looked at. + if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) { log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display()); return Ok(()); } @@ -1084,6 +1086,20 @@ mod tests { use crate::Session; use crate::temp_dir::TempDir; + /// Whether the `.bak` name is taken is asked without following a link there: a dangling link + /// counts as taken, so a file that doesn't look like a drawing leaves it alone. + #[cfg(unix)] + #[test] + fn a_link_at_the_bak_name_counts_as_a_backup_without_being_followed() { + let dir = TempDir::new("cc-bak-link"); + let path = dir.join("plain.dxf"); + std::fs::write(&path, "just some text, not a drawing").unwrap(); + let bak = super::backup_path(&path); + std::os::unix::fs::symlink(dir.join("nowhere"), &bak).unwrap(); + super::backup(&path).unwrap(); + assert!(std::fs::symlink_metadata(&bak).unwrap().file_type().is_symlink(), "the link is left as it was"); + } + /// A backup is never more open than the drawing or the old `.bak`, and loses the group bits when /// it would keep the old `.bak`'s group while the drawing is in another. #[cfg(unix)] diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index dbeab77051..7b36151300 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -47,6 +47,8 @@ struct Table { drawing_dirs: Vec, /// The guards of the drawing folders that have any, by the owner that gave each one. drawing_guards: HashMap>, + /// Guards given once [`MAX_GUARDED_DIRS`] folders had one: they apply to every folder searched. + overflow_guards: Vec<(String, OpenGuard)>, font_dirs: Vec, search_path: Vec, map: Vec<(String, String)>, @@ -152,15 +154,14 @@ fn add_dir(dir: &Path, guard: Option<(&str, OpenGuard)>) { return; } // Guards outlive the drawing list: a folder dropped from it can still be reached as a font - // folder or on the search path. When there is no room for another, the folder isn't searched. - if guard.is_some() && !t.drawing_guards.contains_key(dir) && t.drawing_guards.len() >= MAX_GUARDED_DIRS { - return; - } + // folder or on the search path. When there is no room for another folder's guards, they apply to + // every folder searched from then on, so nothing is left unguarded. + let no_room = !t.drawing_guards.contains_key(dir) && t.drawing_guards.len() >= MAX_GUARDED_DIRS; t.drawing_dirs.retain(|d| d != dir); t.drawing_dirs.insert(0, dir.to_path_buf()); t.drawing_dirs.truncate(MAX_DIRS); if let Some((owner, guard)) = guard { - let guards = t.drawing_guards.entry(dir.to_path_buf()).or_default(); + let guards = if no_room { &mut t.overflow_guards } else { t.drawing_guards.entry(dir.to_path_buf()).or_default() }; guards.retain(|(o, _)| o != owner); guards.push((owner.to_string(), guard)); } @@ -230,7 +231,7 @@ pub fn generation() -> u64 { /// The SHX font file a style or linetype names, if CADCraft can find and read it. pub fn find(name: &str) -> Option> { let mut k = key(name)?; - let (provider, folders, guarded, generation) = { + let (provider, folders, (guarded, overflow), generation) = { let t = table(); // The font map renames once (a map can't loop). if let Some(to) = t.map.iter().find(|(from, _)| *from == k).and_then(|(_, to)| key(to)) { @@ -245,14 +246,16 @@ pub fn find(name: &str) -> Option> { let folders: Vec = t.drawing_dirs.iter().chain(t.font_dirs.iter()).chain(t.search_path.iter()).cloned().collect(); let guarded: Vec<(PathBuf, Vec)> = t.drawing_guards.iter().map(|(d, g)| (d.clone(), g.iter().map(|(_, g)| g.clone()).collect())).collect(); - (t.provider.clone(), folders, guarded, t.generation) + let overflow: Vec = t.overflow_guards.iter().map(|(_, g)| g.clone()).collect(); + (t.provider.clone(), folders, (guarded, overflow), t.generation) }; // A guard belongs to the folder, however the search reaches it: a font folder or the search path // naming the same folder as a drawing's is held to the same guards. let dirs: Vec<(PathBuf, Vec)> = folders .into_iter() .map(|d| { - let guards = guarded.iter().filter(|(g, _)| same_folder(g, &d)).flat_map(|(_, g)| g.iter().cloned()).collect(); + let own = guarded.iter().filter(|(g, _)| same_folder(g, &d)).flat_map(|(_, g)| g.iter().cloned()); + let guards = own.chain(overflow.iter().cloned()).collect(); (d, guards) }) .collect(); diff --git a/crates/fonts/tests/shx_guard_overflow.rs b/crates/fonts/tests/shx_guard_overflow.rs new file mode 100644 index 0000000000..322b314d1e --- /dev/null +++ b/crates/fonts/tests/shx_guard_overflow.rs @@ -0,0 +1,34 @@ +//! Past the number of guarded folders kept, a new folder's guards apply to every folder searched, so +//! no font folder or search path entry is left unguarded. +// Integration tests: unwrapping on failure is fine here, unlike in shipped code (AGENTS.md). +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::path::Path; +use std::sync::Arc; + +use cadcraft_fonts::shx; + +const FONT: &str = "*0,4,overflow\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n"; + +/// With far more guarded folders than are kept, a font folder holding a font the guards refuse still +/// has it refused, and one the guards allow is still found. +#[test] +fn guards_past_the_limit_apply_to_every_folder() { + let bytes = shx::compile(FONT).unwrap(); + let dir = std::env::temp_dir().join(format!("cadcraft-shx-overflow-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("cadcraft-overflow-bad.shx"), &bytes).unwrap(); + std::fs::write(dir.join("cadcraft-overflow-ok.shx"), &bytes).unwrap(); + for n in 0..1100 { + let folder = dir.join(format!("drawings-{n}")); + shx::add_drawing_dir_guarded( + &folder, + "session", + Arc::new(|file: &Path| !file.file_name().is_some_and(|n| n.to_string_lossy().contains("bad"))), + ); + } + shx::set_font_dirs(vec![dir.clone()]); + assert!(shx::find("cadcraft-overflow-bad.shx").is_none(), "refused by a guard given past the limit"); + assert!(shx::find("cadcraft-overflow-ok.shx").is_some()); + std::fs::remove_dir_all(&dir).unwrap(); +} From 61cfaab5af41ec3c0e23a0091dca39d3a602b4fe Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:54:35 +0530 Subject: [PATCH 19/27] Report a case-corrected name the roots refuse as a refusal The probe stopped the search before the refused match could be counted, so a lone case-corrected link out of the roots read as a missing file. The search now says it was refused. --- crates/engine/src/cmd/blocks/xref/load.rs | 37 +++++++++++++---------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index 8b1da3a499..6dd6d20b80 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -226,7 +226,14 @@ pub(crate) fn find(path: &str, host: Option<&Path>, chosen: bool) -> Result c, + Ok(None) => return None, + Err(()) => { + refused_match = true; + return None; + } + }; let ok = allowed(&c); refused_match |= !ok; ok.then_some(c) @@ -246,9 +253,10 @@ const MAX_CASE_SCAN: usize = 10_000; /// The existing file `p` names when its letters' case is ignored, on file systems that don't /// ignore it themselves. Drawings made on Windows often store a reference as `PLAN.DWG` for /// `Plan.dwg`; Windows finds it, and so should Linux. Each missing component is matched against -/// its folder's entries; an exact match always wins, and an ambiguous one finds nothing. +/// its folder's entries; an exact match always wins, and an ambiguous one finds nothing. `Err` when +/// the automation roots refuse a place it would have to look in. #[cfg(not(target_arch = "wasm32"))] -fn case_insensitive(p: &Path) -> Option { +fn case_insensitive(p: &Path) -> Result, ()> { use std::path::Component; // Under the automation roots a place is probed only when the roots allow it, or when it lies on // the way to `p` as it was spelled (which was checked): a name corrected to another case could be @@ -263,29 +271,26 @@ fn case_insensitive(p: &Path) -> Option { }; let exact = out.join(name); if !probe(&exact, corrected) { - return None; + return Err(()); } if exact.exists() { out = exact; continue; } - let want = name.to_str()?.to_lowercase(); - let mut hits = std::fs::read_dir(if out.as_os_str().is_empty() { Path::new(".") } else { &out }) - .ok()? - .take(MAX_CASE_SCAN) - .flatten() - .filter(|e| e.file_name().to_str().is_some_and(|n| n.to_lowercase() == want)); - let hit = hits.next()?; + let Some(want) = name.to_str().map(str::to_lowercase) else { return Ok(None) }; + let Ok(entries) = std::fs::read_dir(if out.as_os_str().is_empty() { Path::new(".") } else { &out }) else { return Ok(None) }; + let mut hits = entries.take(MAX_CASE_SCAN).flatten().filter(|e| e.file_name().to_str().is_some_and(|n| n.to_lowercase() == want)); + let Some(hit) = hits.next() else { return Ok(None) }; if hits.next().is_some() { - return None; + return Ok(None); } out.push(hit.file_name()); corrected = true; if !probe(&out, corrected) { - return None; + return Err(()); } } - out.is_file().then_some(out) + Ok(out.is_file().then_some(out)) } /// Read a drawing file through the host's io hooks, counting its bytes against the load's total. @@ -661,7 +666,7 @@ mod tests { let roots = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); confine(Some(&roots), || { // `alias` isn't there but `Alias` is, a link out: the probe stops before looking in it. - assert_eq!(case_insensitive(&base.join("in/alias/target.dxf")), None); + assert_eq!(case_insensitive(&base.join("in/alias/target.dxf")), Err(())); // A match that leaves the roots doesn't end the search: the next candidate is tried. let host = base.join("in/host.dxf"); let found = find("sub/mixed.dxf", Some(&host), true).unwrap(); @@ -671,7 +676,7 @@ mod tests { std::os::unix::fs::symlink(base.join("outside/target.dxf"), base.join("in/lone/Only.dxf")).unwrap(); assert_eq!(find("lone/only.dxf", Some(&host), true), Err(Missing::OutsideRoots)); }); - assert_eq!(case_insensitive(&base.join("in/alias/target.dxf")), Some(base.join("in/Alias/target.dxf")), "without roots the link is followed"); + assert_eq!(case_insensitive(&base.join("in/alias/target.dxf")), Ok(Some(base.join("in/Alias/target.dxf"))), "without roots the link is followed"); std::fs::remove_dir_all(&base).unwrap(); } From 529b75fb673b1774aee59fb90ef66d232f353a38 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:06:51 +0530 Subject: [PATCH 20/27] Format the new code and assert the walk's seed circle has a handle --- apps/cadcraft-cli/tests/mcp_roots_walk.rs | 1 + crates/engine/src/cmd/blocks/xref/load.rs | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index 6b591b3b6d..3e16d6d397 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -371,6 +371,7 @@ fn walk(tag: &str, roots: bool) -> Walk { let o = f.outside.clone(); let canary = |ext: &str| s(&o.join(format!("canary.{ext}"))); let (circle, table) = seed(&mut server).expect("seed"); + assert!(!circle.is_empty(), "the seed circle has no handle"); assert!(!table.is_empty(), "the seed table has no handle"); for spec in &specs { let id = spec["id"].as_str().unwrap().to_string(); diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index 6dd6d20b80..e543b34e71 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -676,7 +676,11 @@ mod tests { std::os::unix::fs::symlink(base.join("outside/target.dxf"), base.join("in/lone/Only.dxf")).unwrap(); assert_eq!(find("lone/only.dxf", Some(&host), true), Err(Missing::OutsideRoots)); }); - assert_eq!(case_insensitive(&base.join("in/alias/target.dxf")), Ok(Some(base.join("in/Alias/target.dxf"))), "without roots the link is followed"); + assert_eq!( + case_insensitive(&base.join("in/alias/target.dxf")), + Ok(Some(base.join("in/Alias/target.dxf"))), + "without roots the link is followed" + ); std::fs::remove_dir_all(&base).unwrap(); } From e10109e20acda9bd4d7e99bb304b9359ca7ce07e Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:24:24 +0530 Subject: [PATCH 21/27] Document that a reference outside the roots can load a same-named file beside the drawing --- docs/mcp.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index f18e67ce41..e4d18b02b9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -74,8 +74,10 @@ configuration works across the suite) keep the agent to the folders you give it: /work/project/out`, `automation path rejected: UNC paths are refused unless a root is on the same server and share: \\203.0.113.5\s\x.dwg`, or `automation filesystem access is not granted: write authority is absent: /work/project/out/x.png`. -- A file a drawing names is held to the roots too: an image or xref saved with a path outside them - stays unloaded, and the answer doesn't say whether the file exists. +- A file a drawing names is held to the roots too: an image or xref saved with a path outside them is + not loaded from there, and the answer doesn't say whether the file exists. As without roots, a file + of the same name beside the host drawing is tried next, so when one is there and inside the roots + it is loaded in its place: check what a reference loaded when it matters. - A command runs under the roots only if it is classified (`crates/engine/src/file_access/commands.rs`): one nobody classified is refused, whatever it does. `drawingrecovery` is refused, and SAVEFILEPATH can't be changed, because both work on the server's autosave folder. From 6dfcbf29baf22f6e7d2ccf24e09abf709b4b0f2f Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:08:39 +0530 Subject: [PATCH 22/27] Keep every guard given past the limit instead of replacing one with another folder's An owner's guard for a later folder replaced its guard for an earlier one in the shared overflow list, lifting the earlier restriction. Overflow guards now all stay, and refuse everything if they run out. --- crates/fonts/src/shx/table.rs | 23 ++++++++++++++++++++--- crates/fonts/tests/shx_guard_overflow.rs | 2 ++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index 7b36151300..52e02f8a7e 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -35,6 +35,10 @@ const MAX_LOADED_BYTES: usize = 256 << 20; const MAX_DIRS: usize = 32; /// Most folders whose guards are kept. const MAX_GUARDED_DIRS: usize = 1024; +/// Most guards kept past [`MAX_GUARDED_DIRS`], each applying to every folder searched. +const MAX_OVERFLOW_GUARDS: usize = 4096; +/// The owner of the guard that refuses every file once the overflow guards are used up. +const CLOSED: &str = "closed"; /// Most font map entries. const MAX_MAP: usize = 1024; @@ -161,9 +165,22 @@ fn add_dir(dir: &Path, guard: Option<(&str, OpenGuard)>) { t.drawing_dirs.insert(0, dir.to_path_buf()); t.drawing_dirs.truncate(MAX_DIRS); if let Some((owner, guard)) = guard { - let guards = if no_room { &mut t.overflow_guards } else { t.drawing_guards.entry(dir.to_path_buf()).or_default() }; - guards.retain(|(o, _)| o != owner); - guards.push((owner.to_string(), guard)); + if no_room { + // Every overflow guard stays: none may be replaced by another folder's. When even these + // run out, everything is refused from then on. + let kept = &mut t.overflow_guards; + if !kept.iter().any(|(_, g)| Arc::ptr_eq(g, &guard)) { + if kept.len() < MAX_OVERFLOW_GUARDS { + kept.push((owner.to_string(), guard)); + } else if !kept.iter().any(|(o, _)| o == CLOSED) { + kept.push((CLOSED.to_string(), Arc::new(|_: &Path| false))); + } + } + } else { + let guards = t.drawing_guards.entry(dir.to_path_buf()).or_default(); + guards.retain(|(o, _)| o != owner); + guards.push((owner.to_string(), guard)); + } } t.changed(); } diff --git a/crates/fonts/tests/shx_guard_overflow.rs b/crates/fonts/tests/shx_guard_overflow.rs index 322b314d1e..1b0ccab7ff 100644 --- a/crates/fonts/tests/shx_guard_overflow.rs +++ b/crates/fonts/tests/shx_guard_overflow.rs @@ -27,6 +27,8 @@ fn guards_past_the_limit_apply_to_every_folder() { Arc::new(|file: &Path| !file.file_name().is_some_and(|n| n.to_string_lossy().contains("bad"))), ); } + // A later folder with the same owner and a guard that allows everything doesn't lift the others. + shx::add_drawing_dir_guarded(&dir.join("last-drawings"), "session", Arc::new(|_: &Path| true)); shx::set_font_dirs(vec![dir.clone()]); assert!(shx::find("cadcraft-overflow-bad.shx").is_none(), "refused by a guard given past the limit"); assert!(shx::find("cadcraft-overflow-ok.shx").is_some()); From 8b5503e8656f3e90ccf1ac60098de207a97d976c Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:28:52 +0530 Subject: [PATCH 23/27] Require write evidence for the writer controls and read evidence for the reader controls --- apps/cadcraft-cli/tests/mcp_roots_walk.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index 3e16d6d397..c298f01e47 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -538,8 +538,11 @@ fn the_walk_finds_escapes_without_roots() { "tool:render", "lisp:code", ]; + // What a command touched is kept with its kind (`wrote`, `created`, `removed`, `read`): a writer + // must show a write, not just a read, or a writer that only reads would still pass. + let kinds = |id: &str, kinds: &[&str]| w.escapes.get(id).is_some_and(|e| e.iter().any(|l| kinds.iter().any(|k| l.starts_with(k)))); for id in writers { - assert!(found.contains(id), "the walk no longer finds `{id}` writing outside: {found:?}"); + assert!(kinds(id, &["wrote ", "created ", "removed "]), "the walk no longer finds `{id}` writing outside: {found:?}"); } if w.sees_reads { for id in [ @@ -564,7 +567,7 @@ fn the_walk_finds_escapes_without_roots() { "setvar:QNEWTEMPLATE", "setvar:SAVEFILEPATH", ] { - assert!(found.contains(id), "the walk no longer finds `{id}` reading outside: {found:?}"); + assert!(kinds(id, &["read "]), "the walk no longer finds `{id}` reading outside: {found:?}"); } } } From f097a688fe419ec1c80a69559cf1421172071d00 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:02:25 +0530 Subject: [PATCH 24/27] Count plottermanager as a reader in the control walk, and list every writer that shows no write --- apps/cadcraft-cli/tests/mcp_roots_walk.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index c298f01e47..79fd53ad43 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -530,7 +530,6 @@ fn the_walk_finds_escapes_without_roots() { "layout.saveas", "layout", "stylesmanager", - "plottermanager", "tableexport", "dataextraction", "tool:save", @@ -541,9 +540,8 @@ fn the_walk_finds_escapes_without_roots() { // What a command touched is kept with its kind (`wrote`, `created`, `removed`, `read`): a writer // must show a write, not just a read, or a writer that only reads would still pass. let kinds = |id: &str, kinds: &[&str]| w.escapes.get(id).is_some_and(|e| e.iter().any(|l| kinds.iter().any(|k| l.starts_with(k)))); - for id in writers { - assert!(kinds(id, &["wrote ", "created ", "removed "]), "the walk no longer finds `{id}` writing outside: {found:?}"); - } + let not_writing: Vec<&str> = writers.into_iter().filter(|id| !kinds(id, &["wrote ", "created ", "removed "])).collect(); + assert!(not_writing.is_empty(), "the walk no longer finds these writing outside: {not_writing:?}; touched: {:?}", w.escapes); if w.sees_reads { for id in [ "open", @@ -561,6 +559,7 @@ fn the_walk_finds_escapes_without_roots() { "aliasedit", "linetype", "hatch.patterns", + "plottermanager", "appload", "datalink", "tool:open", From de6b841d6a343a77669f9e789da34522310ecb03 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:23:58 +0530 Subject: [PATCH 25/27] Track a full overflow list with a flag, not an owner name --- crates/fonts/src/shx/table.rs | 13 ++++++++----- crates/fonts/tests/shx_guard_closed.rs | 27 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) create mode 100644 crates/fonts/tests/shx_guard_closed.rs diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index 52e02f8a7e..7fa11a216d 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -37,8 +37,6 @@ const MAX_DIRS: usize = 32; const MAX_GUARDED_DIRS: usize = 1024; /// Most guards kept past [`MAX_GUARDED_DIRS`], each applying to every folder searched. const MAX_OVERFLOW_GUARDS: usize = 4096; -/// The owner of the guard that refuses every file once the overflow guards are used up. -const CLOSED: &str = "closed"; /// Most font map entries. const MAX_MAP: usize = 1024; @@ -53,6 +51,8 @@ struct Table { drawing_guards: HashMap>, /// Guards given once [`MAX_GUARDED_DIRS`] folders had one: they apply to every folder searched. overflow_guards: Vec<(String, OpenGuard)>, + /// The overflow guards ran out: every file is refused from then on. + overflow_closed: bool, font_dirs: Vec, search_path: Vec, map: Vec<(String, String)>, @@ -172,8 +172,8 @@ fn add_dir(dir: &Path, guard: Option<(&str, OpenGuard)>) { if !kept.iter().any(|(_, g)| Arc::ptr_eq(g, &guard)) { if kept.len() < MAX_OVERFLOW_GUARDS { kept.push((owner.to_string(), guard)); - } else if !kept.iter().any(|(o, _)| o == CLOSED) { - kept.push((CLOSED.to_string(), Arc::new(|_: &Path| false))); + } else { + t.overflow_closed = true; } } } else { @@ -263,7 +263,10 @@ pub fn find(name: &str) -> Option> { let folders: Vec = t.drawing_dirs.iter().chain(t.font_dirs.iter()).chain(t.search_path.iter()).cloned().collect(); let guarded: Vec<(PathBuf, Vec)> = t.drawing_guards.iter().map(|(d, g)| (d.clone(), g.iter().map(|(_, g)| g.clone()).collect())).collect(); - let overflow: Vec = t.overflow_guards.iter().map(|(_, g)| g.clone()).collect(); + let mut overflow: Vec = t.overflow_guards.iter().map(|(_, g)| g.clone()).collect(); + if t.overflow_closed { + overflow.push(Arc::new(|_: &Path| false)); + } (t.provider.clone(), folders, (guarded, overflow), t.generation) }; // A guard belongs to the folder, however the search reaches it: a font folder or the search path diff --git a/crates/fonts/tests/shx_guard_closed.rs b/crates/fonts/tests/shx_guard_closed.rs new file mode 100644 index 0000000000..c181360d1e --- /dev/null +++ b/crates/fonts/tests/shx_guard_closed.rs @@ -0,0 +1,27 @@ +//! When even the overflow guards run out, every font is refused, whatever name the owners gave. +// Integration tests: unwrapping on failure is fine here, unlike in shipped code (AGENTS.md). +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::path::Path; +use std::sync::Arc; + +use cadcraft_fonts::shx; + +const FONT: &str = "*0,4,closed\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n"; + +/// Past every limit, a font that no guard objects to is still refused, also when an owner is called +/// `closed`. +#[test] +fn guards_that_ran_out_refuse_every_font() { + let bytes = shx::compile(FONT).unwrap(); + let dir = std::env::temp_dir().join(format!("cadcraft-shx-closed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("cadcraft-closed-ok.shx"), &bytes).unwrap(); + shx::set_font_dirs(vec![dir.clone()]); + assert!(shx::find("cadcraft-closed-ok.shx").is_some(), "found while nothing guards the folder"); + for n in 0..6000 { + shx::add_drawing_dir_guarded(&dir.join(format!("drawings-{n}")), "closed", Arc::new(|_: &Path| true)); + } + assert!(shx::find("cadcraft-closed-ok.shx").is_none(), "refused once the guards ran out"); + std::fs::remove_dir_all(&dir).unwrap(); +} From b42d54a36821c25a6c7740fd07a6ea315c98632e Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:49:44 +0530 Subject: [PATCH 26/27] Give the font guard tests an exclusive, self-cleaning folder and resolve folders once per lookup --- crates/fonts/src/shx/table.rs | 11 ++++----- crates/fonts/tests/shx_guard.rs | 31 ++++++++++++++++++------ crates/fonts/tests/shx_guard_closed.rs | 29 +++++++++++++++++++--- crates/fonts/tests/shx_guard_overflow.rs | 29 +++++++++++++++++++--- 4 files changed, 81 insertions(+), 19 deletions(-) diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index 7fa11a216d..42fa0b72af 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -271,10 +271,14 @@ pub fn find(name: &str) -> Option> { }; // A guard belongs to the folder, however the search reaches it: a font folder or the search path // naming the same folder as a drawing's is held to the same guards. + // Each folder is resolved once per lookup (spelled, and as the file system has it). + let resolved = |d: &Path| std::fs::canonicalize(d).ok(); + let guarded: Vec<(PathBuf, Option, Vec)> = guarded.into_iter().map(|(d, g)| (d.clone(), resolved(&d), g)).collect(); let dirs: Vec<(PathBuf, Vec)> = folders .into_iter() .map(|d| { - let own = guarded.iter().filter(|(g, _)| same_folder(g, &d)).flat_map(|(_, g)| g.iter().cloned()); + let real = resolved(&d); + let own = guarded.iter().filter(|(g, r, _)| *g == d || (real.is_some() && *r == real)).flat_map(|(_, _, g)| g.iter().cloned()); let guards = own.chain(overflow.iter().cloned()).collect(); (d, guards) }) @@ -304,11 +308,6 @@ pub fn find(name: &str) -> Option> { font } -/// Do `a` and `b` name the same folder, as spelled or once the file system has resolved them? -fn same_folder(a: &Path, b: &Path) -> bool { - a == b || matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b) -} - /// Most directory entries looked at for a font file whose name differs only in case. #[cfg(not(target_arch = "wasm32"))] const MAX_DIR_ENTRIES: usize = 10_000; diff --git a/crates/fonts/tests/shx_guard.rs b/crates/fonts/tests/shx_guard.rs index 11f89dc930..412e1689eb 100644 --- a/crates/fonts/tests/shx_guard.rs +++ b/crates/fonts/tests/shx_guard.rs @@ -10,11 +10,28 @@ use cadcraft_fonts::shx; const FONT: &str = "*0,4,guard\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n"; -/// A new folder of this test's own. -fn fresh_dir() -> PathBuf { - let dir = std::env::temp_dir().join(format!("cadcraft-shx-guard-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - dir +/// A folder of this test's own, made here so nothing else put it there first, and removed when the +/// test ends, also when it fails. +struct TestDir(std::path::PathBuf); + +impl Drop for TestDir { + /// Removes the folder and all it holds. + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A new folder for `tag`: creating it must not find one already there. +fn fresh_dir(tag: &str) -> TestDir { + let mut n = 0u32; + loop { + let dir = std::env::temp_dir().join(format!("cadcraft-shx-{tag}-{}-{n}", std::process::id())); + match std::fs::create_dir(&dir) { + Ok(()) => return TestDir(dir), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, + Err(e) => panic!("{}: {e}", dir.display()), + } + } } /// The lower-case file name of `file`, so a guard never reads the test folder's own name. @@ -27,7 +44,8 @@ fn name(file: &Path) -> String { #[test] fn every_file_the_search_opens_goes_to_the_guard_first() { let bytes = shx::compile(FONT).unwrap(); - let dir = fresh_dir(); + let owner = fresh_dir("guard"); + let dir = owner.0.clone(); std::fs::write(dir.join("cadcraft-guard-ok.shx"), &bytes).unwrap(); std::fs::write(dir.join("cadcraft-guard-bad.shx"), &bytes).unwrap(); // Found only by looking through the folder, as a link under another spelling would be. @@ -79,5 +97,4 @@ fn every_file_the_search_opens_goes_to_the_guard_first() { assert!(!shx::drawing_dirs().contains(&dir)); assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "the outside font stays rejected after the eviction"); assert!(shx::find("cadcraft-guard-ok.shx").is_some()); - std::fs::remove_dir_all(&dir).unwrap(); } diff --git a/crates/fonts/tests/shx_guard_closed.rs b/crates/fonts/tests/shx_guard_closed.rs index c181360d1e..34a74ca7c4 100644 --- a/crates/fonts/tests/shx_guard_closed.rs +++ b/crates/fonts/tests/shx_guard_closed.rs @@ -9,13 +9,37 @@ use cadcraft_fonts::shx; const FONT: &str = "*0,4,closed\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n"; +/// A folder of this test's own, made here so nothing else put it there first, and removed when the +/// test ends, also when it fails. +struct TestDir(std::path::PathBuf); + +impl Drop for TestDir { + /// Removes the folder and all it holds. + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A new folder for `tag`: creating it must not find one already there. +fn fresh_dir(tag: &str) -> TestDir { + let mut n = 0u32; + loop { + let dir = std::env::temp_dir().join(format!("cadcraft-shx-{tag}-{}-{n}", std::process::id())); + match std::fs::create_dir(&dir) { + Ok(()) => return TestDir(dir), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, + Err(e) => panic!("{}: {e}", dir.display()), + } + } +} + /// Past every limit, a font that no guard objects to is still refused, also when an owner is called /// `closed`. #[test] fn guards_that_ran_out_refuse_every_font() { let bytes = shx::compile(FONT).unwrap(); - let dir = std::env::temp_dir().join(format!("cadcraft-shx-closed-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let owner = fresh_dir("closed"); + let dir = owner.0.clone(); std::fs::write(dir.join("cadcraft-closed-ok.shx"), &bytes).unwrap(); shx::set_font_dirs(vec![dir.clone()]); assert!(shx::find("cadcraft-closed-ok.shx").is_some(), "found while nothing guards the folder"); @@ -23,5 +47,4 @@ fn guards_that_ran_out_refuse_every_font() { shx::add_drawing_dir_guarded(&dir.join(format!("drawings-{n}")), "closed", Arc::new(|_: &Path| true)); } assert!(shx::find("cadcraft-closed-ok.shx").is_none(), "refused once the guards ran out"); - std::fs::remove_dir_all(&dir).unwrap(); } diff --git a/crates/fonts/tests/shx_guard_overflow.rs b/crates/fonts/tests/shx_guard_overflow.rs index 1b0ccab7ff..8482977e17 100644 --- a/crates/fonts/tests/shx_guard_overflow.rs +++ b/crates/fonts/tests/shx_guard_overflow.rs @@ -10,13 +10,37 @@ use cadcraft_fonts::shx; const FONT: &str = "*0,4,overflow\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n"; +/// A folder of this test's own, made here so nothing else put it there first, and removed when the +/// test ends, also when it fails. +struct TestDir(std::path::PathBuf); + +impl Drop for TestDir { + /// Removes the folder and all it holds. + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A new folder for `tag`: creating it must not find one already there. +fn fresh_dir(tag: &str) -> TestDir { + let mut n = 0u32; + loop { + let dir = std::env::temp_dir().join(format!("cadcraft-shx-{tag}-{}-{n}", std::process::id())); + match std::fs::create_dir(&dir) { + Ok(()) => return TestDir(dir), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, + Err(e) => panic!("{}: {e}", dir.display()), + } + } +} + /// With far more guarded folders than are kept, a font folder holding a font the guards refuse still /// has it refused, and one the guards allow is still found. #[test] fn guards_past_the_limit_apply_to_every_folder() { let bytes = shx::compile(FONT).unwrap(); - let dir = std::env::temp_dir().join(format!("cadcraft-shx-overflow-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let owner = fresh_dir("overflow"); + let dir = owner.0.clone(); std::fs::write(dir.join("cadcraft-overflow-bad.shx"), &bytes).unwrap(); std::fs::write(dir.join("cadcraft-overflow-ok.shx"), &bytes).unwrap(); for n in 0..1100 { @@ -32,5 +56,4 @@ fn guards_past_the_limit_apply_to_every_folder() { shx::set_font_dirs(vec![dir.clone()]); assert!(shx::find("cadcraft-overflow-bad.shx").is_none(), "refused by a guard given past the limit"); assert!(shx::find("cadcraft-overflow-ok.shx").is_some()); - std::fs::remove_dir_all(&dir).unwrap(); } From 8cbade6ec3b785161e43f090cbf210d7709751fd Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:45:33 +0530 Subject: [PATCH 27/27] Ask the guards about a font folder before listing it, and document command_line refusals separately --- crates/fonts/src/shx/table.rs | 4 ++ crates/fonts/tests/shx_guard_listing.rs | 55 +++++++++++++++++++++++++ docs/mcp.md | 3 ++ 3 files changed, 62 insertions(+) create mode 100644 crates/fonts/tests/shx_guard_listing.rs diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index 42fa0b72af..8f2e69aa98 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -354,6 +354,10 @@ fn read_from(dirs: &[(PathBuf, Vec)], name: &str) -> Option> if let Some(b) = [d.join(name), d.join(name.to_ascii_uppercase())].iter().find_map(|f| read(f)) { return Some(b); } + // The folder is listed only when its guards allow the folder itself. + if !guards.iter().all(|g| g(d)) { + continue; + } let Ok(entries) = std::fs::read_dir(d) else { continue }; let found = entries .take(MAX_DIR_ENTRIES) diff --git a/crates/fonts/tests/shx_guard_listing.rs b/crates/fonts/tests/shx_guard_listing.rs new file mode 100644 index 0000000000..98244ddc95 --- /dev/null +++ b/crates/fonts/tests/shx_guard_listing.rs @@ -0,0 +1,55 @@ +//! A guarded folder is listed only when its guards allow the folder itself, so a folder outside the +//! automation roots isn't read even for the names in it. +// Integration tests: unwrapping on failure is fine here, unlike in shipped code (AGENTS.md). +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use cadcraft_fonts::shx; + +/// A folder of this test's own, made here so nothing else put it there first, and removed when the +/// test ends, also when it fails. +struct TestDir(PathBuf); + +impl Drop for TestDir { + /// Removes the folder and all it holds. + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A new folder: creating it must not find one already there. +fn fresh_dir() -> TestDir { + let mut n = 0u32; + loop { + let dir = std::env::temp_dir().join(format!("cadcraft-shx-listing-{}-{n}", std::process::id())); + match std::fs::create_dir(&dir) { + Ok(()) => return TestDir(dir), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, + Err(e) => panic!("{}: {e}", dir.display()), + } + } +} + +/// Looking for a font that isn't there makes the search list the folder, and the guard is asked +/// about the folder itself first; a guard that refuses it ends the search there. +#[test] +fn the_folder_itself_goes_to_the_guard_before_it_is_listed() { + let owner = fresh_dir(); + let dir = owner.0.clone(); + let asked: Arc>> = Arc::default(); + let log = asked.clone(); + let folder = dir.clone(); + shx::add_drawing_dir_guarded( + &dir, + "listing", + Arc::new(move |path: &Path| { + log.lock().unwrap().push(path.to_path_buf()); + path != folder + }), + ); + assert!(shx::find("cadcraft-listing-missing.shx").is_none()); + let seen = asked.lock().unwrap().clone(); + assert!(seen.contains(&dir), "the guard was asked about the folder: {seen:?}"); +} diff --git a/docs/mcp.md b/docs/mcp.md index e4d18b02b9..492ad05c16 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -74,6 +74,9 @@ configuration works across the suite) keep the agent to the folders you give it: /work/project/out`, `automation path rejected: UNC paths are refused unless a root is on the same server and share: \\203.0.113.5\s\x.dwg`, or `automation filesystem access is not granted: write authority is absent: /work/project/out/x.png`. +- A refused path in a `command_line` line is not a tool error: the reply is an ordinary result, with + the refusal in its `error` field (and echoed in `output`) and without `isError`. A client that + drives `command_line` has to read `error`. - A file a drawing names is held to the roots too: an image or xref saved with a path outside them is not loaded from there, and the answer doesn't say whether the file exists. As without roots, a file of the same name beside the host drawing is tried next, so when one is there and inside the roots