From 7362530591265a931b624524038c960c766be51d Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 20:30:07 +0200 Subject: [PATCH] MCP: --automation-read-root and --automation-write-root may each be given more than once (#1552) A path passes when it lies inside one of the roots of its kind. The roots' common parent, a sibling named like a root, `..` or a link out of them and the other kind's roots stay refused; a folder given twice counts once. --- ROADMAP.md | 1 + apps/designcraft-cli/src/automation_args.rs | 56 +++--- apps/designcraft-cli/src/main.rs | 15 +- apps/designcraft-cli/tests/it/cli.rs | 78 +++++++- crates/engine/src/file_access.rs | 210 ++++++++++++++++---- crates/engine/src/tests_roots.rs | 2 +- crates/mcp/tests/it/automation_roots.rs | 4 +- docs/mcp.md | 29 ++- 8 files changed, 300 insertions(+), 95 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index d3ef17e47..588c46923 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -348,6 +348,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-23** · `designcraft-cli mcp` takes `--automation-read-root` and `--automation-write-root` more than once, as the suite's other apps do (#1552): a path inside any root of its kind passes, and the roots' common parent, `..` or a link out of them and the other kind's roots stay refused. No readiness percentage change. - **2026-10-16** · Edit › Keyboard Shortcuts imports a set saved by InDesign's Show Set (.txt, Windows or Mac key names, UTF-8 or UTF-16): matched commands take its Default shortcuts or lose theirs, other commands give up keys it takes, and a report lists what it changed and the items it could not match (`window.importShortcuts`, #1180). Tool keys stay fixed. No readiness percentage change. - **2026-10-22** · A ruler guide dragged with the Selection tools, out of a ruler, on its own or with other selected guides, snaps along its axis as objects do (#1221): to other ruler guides, margins, columns, bleed, page and object edges and centers (with the smart-guide mark) and the document grid, within the snap zone and following Snap to Guides and Smart Guides. Shift snaps to the ruler's ticks and Cmd suspends snapping. The preview line, the position readout and the drop use the same snapped position. No readiness percentage change. - **2026-10-22** · macOS: the app menu has a Language submenu after Settings… with each interface language in its own name and the current one checked, as in the suite's other apps; Preferences › General › Interface Language stays. No readiness percentage change. diff --git a/apps/designcraft-cli/src/automation_args.rs b/apps/designcraft-cli/src/automation_args.rs index 52ef34f20..2ad9af786 100644 --- a/apps/designcraft-cli/src/automation_args.rs +++ b/apps/designcraft-cli/src/automation_args.rs @@ -3,30 +3,22 @@ use std::path::PathBuf; +#[derive(Default)] pub struct AutomationArgs { - pub read_root: Option, - pub write_root: Option, - read_given: bool, - write_given: bool, + pub read_roots: Vec, + pub write_roots: Vec, } impl AutomationArgs { - pub fn new(read_root: Option, write_root: Option) -> Self { - Self { read_root, write_root, read_given: false, write_given: false } - } - - /// Returns whether this argument is a root flag. A second occurrence of a flag is an error, - /// including when the two spellings (`--flag DIR`, `--flag=DIR`) are mixed. + /// Returns whether this argument is a root flag. Each flag may be given more than once (#1552), + /// in either spelling (`--flag DIR`, `--flag=DIR`): every use adds a folder, none replaces one. pub fn consume(&mut self, arg: &str, args: &mut impl Iterator) -> Result { let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value))); - let (root, given) = match flag { - "--automation-read-root" => (&mut self.read_root, &mut self.read_given), - "--automation-write-root" => (&mut self.write_root, &mut self.write_given), + let roots = match flag { + "--automation-read-root" => &mut self.read_roots, + "--automation-write-root" => &mut self.write_roots, _ => return Ok(false), }; - if *given { - return Err(format!("{flag} given twice")); - } let value = match inline { Some(value) => value.to_owned(), None => { @@ -40,8 +32,7 @@ impl AutomationArgs { if value.is_empty() { return Err(format!("{flag} needs a non-empty folder")); } - *root = Some(value.into()); - *given = true; + roots.push(value.into()); Ok(true) } } @@ -51,40 +42,43 @@ mod tests { use super::*; #[test] - fn roots_are_taken_once_and_other_arguments_are_left() { - let mut roots = AutomationArgs::new(None, None); + fn roots_add_up_and_other_arguments_are_left() { + let mut roots = AutomationArgs::default(); let mut args = ["a folder".to_owned(), "doc.designcraft".to_owned()].into_iter(); assert!(roots.consume("--automation-read-root", &mut args).unwrap()); assert!(roots.consume("--automation-write-root=out", &mut args).unwrap()); assert!(!roots.consume("--sample", &mut args).unwrap()); - assert_eq!(roots.read_root, Some("a folder".into())); - assert_eq!(roots.write_root, Some("out".into())); + assert_eq!(roots.read_roots, [PathBuf::from("a folder")]); + assert_eq!(roots.write_roots, [PathBuf::from("out")]); assert_eq!(args.next().as_deref(), Some("doc.designcraft")); - assert!(roots.consume("--automation-read-root=other", &mut args).is_err()); - assert_eq!(roots.read_root, Some("a folder".into())); + // #1552: a flag given again adds a folder, in either spelling, and keeps the first. + assert!(roots.consume("--automation-read-root=other", &mut args).unwrap()); + assert!(roots.consume("--automation-write-root", &mut ["out2".to_owned()].into_iter()).unwrap()); + assert_eq!(roots.read_roots, [PathBuf::from("a folder"), PathBuf::from("other")]); + assert_eq!(roots.write_roots, [PathBuf::from("out"), PathBuf::from("out2")]); } #[test] fn invalid_operands_leave_roots_unchanged() { for flag in ["--automation-read-root", "--automation-write-root"] { for operand in [None, Some(""), Some("--version"), Some("--connect"), Some("-folder")] { - let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into())); + let mut roots = AutomationArgs { read_roots: vec!["read".into()], write_roots: vec!["write".into()] }; let mut args = operand.map(str::to_owned).into_iter(); assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}"); - assert_eq!(roots.read_root, Some("read".into())); - assert_eq!(roots.write_root, Some("write".into())); + assert_eq!(roots.read_roots, [PathBuf::from("read")]); + assert_eq!(roots.write_roots, [PathBuf::from("write")]); } - let mut roots = AutomationArgs::new(None, None); + let mut roots = AutomationArgs::default(); assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err()); } } #[test] fn explicit_dash_folder_and_relative_dash_folder_are_valid() { - let mut roots = AutomationArgs::new(None, None); + let mut roots = AutomationArgs::default(); assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap()); assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap()); - assert_eq!(roots.read_root, Some("-folder".into())); - assert_eq!(roots.write_root, Some("./-folder".into())); + assert_eq!(roots.read_roots, [PathBuf::from("-folder")]); + assert_eq!(roots.write_roots, [PathBuf::from("./-folder")]); } } diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 71e05a480..99dd49afe 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -10,7 +10,7 @@ //! # run a command script (crates/engine/src/script.rs): `$N.path` references //! designcraft-cli app [--port PORT] COMMAND [JSON] # run a command in the running app (designcraft --control PORT) //! designcraft-cli app [--port PORT] --method METHOD [JSON] # any control-channel method (ui.screenshot, ui.render, …) -//! designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR] [--automation-write-root DIR] +//! designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]... //! # MCP server over stdio (docs/mcp.md); the roots confine the files it reads and writes //! designcraft-cli perf [--pages N] [--frames N] [--chars N] [--images N] [--runs N] [--strict] # budgets on a synthetic stress document //! designcraft-cli bench FILE [--runs N] # the same measurements on one document @@ -39,7 +39,7 @@ use designcraft_engine::Session; use serde_json::{Value, json}; /// The usage block. Shared by `--help` (stdout, success) and an unknown command (stderr, failure). -const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR] [--automation-write-root DIR]\n the two roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. A root left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli links\n designcraft-cli --version"; +const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...\n the roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. Each may be given more than once; a kind\n left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli links\n designcraft-cli --version"; /// `script --help`: the script syntax, otherwise only in `describe script.run` and docs/agents.md. const SCRIPT_HELP: &str = r#"usage: designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going] @@ -170,7 +170,7 @@ fn mcp(args: &[String]) -> Result<(), String> { use designcraft_mcp::{Backend, Headless, Remote, Server, control_addr}; let mut connect: Option = None; let mut sample = false; - let mut roots_args = automation_args::AutomationArgs::new(None, None); + let mut roots_args = automation_args::AutomationArgs::default(); let mut it = args.iter().cloned(); while let Some(a) = it.next() { if roots_args.consume(&a, &mut it)? { @@ -181,12 +181,14 @@ fn mcp(args: &[String]) -> Result<(), String> { "--sample" => sample = true, other => { return Err(format!( - "unknown mcp option `{other}` (usage: designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR] [--automation-write-root DIR])" + "unknown mcp option `{other}` (usage: designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...)" )); } } } - let roots = AutomationRoots::new(roots_args.read_root.as_deref(), roots_args.write_root.as_deref())?; + let read: Vec<&std::path::Path> = roots_args.read_roots.iter().map(std::path::PathBuf::as_path).collect(); + let write: Vec<&std::path::Path> = roots_args.write_roots.iter().map(std::path::PathBuf::as_path).collect(); + let roots = AutomationRoots::new(&read, &write)?; if roots.is_some() && connect.is_some() { return Err("--automation-read-root and --automation-write-root confine the in-process server; a running app is not confined by them, \ so drop --connect (or use --connect without the roots)" @@ -209,8 +211,7 @@ so drop --connect (or use --connect without the roots)" if let Some(roots) = roots { // Every thread of this process, not only the server's: nothing reaches past the roots. file_access::confine_process(roots.clone()); - let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string()); - eprintln!("designcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root())); + eprintln!("designcraft-cli: files confined: {}", roots.describe()); h = h.with_automation_roots(Some(roots)); } Box::new(h) diff --git a/apps/designcraft-cli/tests/it/cli.rs b/apps/designcraft-cli/tests/it/cli.rs index 173a605f4..467b231f6 100644 --- a/apps/designcraft-cli/tests/it/cli.rs +++ b/apps/designcraft-cli/tests/it/cli.rs @@ -401,6 +401,76 @@ fn mcp_automation_roots_confine_the_server() { let _ = std::fs::remove_dir_all(base); } +/// #1552: each root flag may be given more than once. A path inside any root of its kind passes; +/// the roots' common parent, a sibling whose name starts like a root's, `..` out of a root, the +/// other kind's roots and a link out of a root stay refused. +#[test] +fn mcp_automation_roots_take_several_folders() { + let base = std::env::temp_dir().join(format!("dc-cli-roots-several-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["in", "shared", "out", "scratch", "outside", "in2", "scratch2"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + // Resolved, as the server shows the roots (`/var` is `/private/var` on macOS). + let base = std::fs::canonicalize(base).unwrap(); + for f in ["in/a.designcraft", "shared/b.designcraft", "outside/secret.designcraft", "parent.designcraft", "in2/c.designcraft"] { + make_document(&base.join(f)); + } + let p = |f: &str| base.join(f).to_str().unwrap().to_string(); + let sep = std::path::MAIN_SEPARATOR; + let up = |root: &str, rest: &str| format!("{}{sep}..{sep}{rest}", p(root)); + let calls = [ + ("open_document", serde_json::json!({"path": p("in/a.designcraft")})), + ("open_document", serde_json::json!({"path": p("shared/b.designcraft")})), + // The roots' common parent is not a root. + ("open_document", serde_json::json!({"path": p("parent.designcraft")})), + ("open_document", serde_json::json!({"path": up("shared", &format!("outside{sep}secret.designcraft"))})), + // `in2` only starts like `in`. + ("open_document", serde_json::json!({"path": p("in2/c.designcraft")})), + // `..` from one read root into another stays inside. + ("open_document", serde_json::json!({"path": up("shared", &format!("in{sep}a.designcraft"))})), + ("save_document", serde_json::json!({"path": p("out/x.designcraft")})), + ("save_document", serde_json::json!({"path": p("scratch/y.designcraft")})), + ("save_document", serde_json::json!({"path": p("z.designcraft")})), + ("save_document", serde_json::json!({"path": p("scratch2/z.designcraft")})), + // Read and write stay separate: a read root is not a write root, nor the other way round. + ("save_document", serde_json::json!({"path": p("shared/w.designcraft")})), + ("open_document", serde_json::json!({"path": p("out/x.designcraft")})), + ("export_png", serde_json::json!({"path": up("scratch", &format!("outside{sep}p.png"))})), + ]; + let read2 = format!("--automation-read-root={}", p("shared")); + let args = ["--automation-read-root", &p("in"), &read2, "--automation-write-root", &p("out"), "--automation-write-root", &p("scratch")]; + let (success, stderr, replies) = mcp_session(&args, &calls); + assert!(success, "{stderr}"); + let confined = format!("files confined: read {}, {}; write {}, {}", p("in"), p("shared"), p("out"), p("scratch")); + assert!(stderr.contains(&confined), "{stderr}"); + let errors: Vec = replies.iter().map(|r| r["result"]["isError"] == true).collect(); + assert_eq!(errors, [false, false, true, true, true, false, false, false, true, true, true, true, true], "{replies:?}"); + for (i, kind) in [(2, "read"), (3, "read"), (4, "read"), (8, "write"), (9, "write"), (10, "write"), (11, "read"), (12, "write")] { + assert!(text(&replies[i]).contains(&format!("outside the {kind} roots ")), "{i}: {}", text(&replies[i])); + } + assert!(base.join("out/x.designcraft").is_file() && base.join("scratch/y.designcraft").is_file()); + for f in ["z.designcraft", "scratch2/z.designcraft", "shared/w.designcraft", "outside/p.png"] { + assert!(!base.join(f).exists(), "{f} was written outside the write roots"); + } + + // A link in one root that leads out of all of them is outside, for reading and for writing. + #[cfg(unix)] + { + std::os::unix::fs::symlink(base.join("outside/secret.designcraft"), base.join("shared/leak.designcraft")).unwrap(); + std::os::unix::fs::symlink(base.join("outside"), base.join("scratch/away")).unwrap(); + let calls = [ + ("open_document", serde_json::json!({"path": p("shared/leak.designcraft")})), + ("save_document", serde_json::json!({"path": p("scratch/away/x.designcraft")})), + ]; + let (_, _, replies) = mcp_session(&args, &calls); + assert!(text(&replies[0]).contains("outside the read roots"), "{}", text(&replies[0])); + assert!(text(&replies[1]).contains("outside the write roots"), "{}", text(&replies[1])); + assert!(!base.join("outside/x.designcraft").exists()); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn mcp_automation_root_flags_are_checked_up_front() { let base = std::env::temp_dir().join(format!("dc-cli-roots-args-{}", std::process::id())); @@ -419,9 +489,11 @@ fn mcp_automation_root_flags_are_checked_up_front() { // The flags confine the in-process server, so they cannot be combined with --connect. fails(&["--connect", "7979", "--automation-read-root", dir], "--connect"); fails(&["--automation-write-root", dir, "--connect", "7979"], "--connect"); - fails(&["--automation-read-root", dir, "--automation-read-root", dir], "given twice"); - fails(&["--automation-write-root", dir, "--automation-write-root", dir], "given twice"); - fails(&["--automation-read-root", dir, "--automation-read-root=x"], "given twice"); + // #1552: a flag may be given again, but every folder it names must exist and be given. + fails(&["--automation-read-root", dir, "--automation-read-root", missing.to_str().unwrap()], "cannot open the automation read root"); + fails(&["--automation-write-root", missing.to_str().unwrap(), "--automation-write-root", dir], "cannot open the automation write root"); + fails(&["--automation-write-root", dir, "--automation-write-root"], "needs a folder"); + fails(&["--automation-read-root", dir, "--automation-read-root="], "needs a non-empty folder"); fails(&["--automation-read-root"], "needs a folder"); fails(&["--automation-write-root", "--sample"], "needs a folder"); fails(&["--automation-read-root", missing.to_str().unwrap()], "cannot open the automation read root"); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 4f9a17c6f..31d61e382 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -1,15 +1,17 @@ //! The folders automation may read and write. //! //! `designcraft-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`]: +//! files an agent's commands reach; each flag may be given more than once (#1552). [`AutomationRoots`] +//! holds the folders of each kind. 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. +//! - The result must lie inside one of the roots of its kind, compared by whole components +//! (`/work2` isn't inside `/work`), without regard to case on Windows. Two roots don't make their +//! common parent one. //! - Read and write access are separate: a root given alone grants only its own kind of access. //! //! Roots are in force on a thread inside [`confine`], and in the whole process after @@ -32,11 +34,11 @@ pub enum Access { Write, } -/// The folders automation may read and write; a root left out grants no access of its kind. +/// The folders automation may read and write; a kind with no root grants no access of its kind. #[derive(Debug)] pub struct AutomationRoots { - read: Option, - write: Option, + read: Vec, + write: Vec, } #[derive(Debug)] @@ -62,47 +64,61 @@ impl Root { } 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() { + /// The roots `read` and `write`, which must be existing folders (one given twice counts once); + /// `None` when neither kind has any (nothing is confined then). + pub fn new(read: &[&Path], write: &[&Path]) -> Result>, String> { + if read.is_empty() && write.is_empty() { 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 }))) + let open = |paths: &[&Path], access: Access| -> Result, String> { + let mut roots: Vec = Vec::with_capacity(paths.len()); + for path in paths { + let root = Root::open(path, access)?; + if !roots.iter().any(|r| r.resolved == root.resolved) { + roots.push(root); + } + } + Ok(roots) + }; + Ok(Some(Arc::new(Self { read: open(read, Access::Read)?, write: open(write, Access::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 roots for people: `read A, B; write C` (`none` for a kind without any), absolute with + /// their links followed. + pub fn describe(&self) -> String { + let list = |roots: &[Root]| { + if roots.is_empty() { + return "none".to_string(); + } + roots.iter().map(|r| r.shown.display().to_string()).collect::>().join(", ") + }; + format!("read {}; write {}", list(&self.read), list(&self.write)) } - /// 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. + /// May the file or folder at `path` be read (or written)? It must lie inside one of the roots + /// of that kind. `Err` says why not. pub fn check(&self, path: impl AsRef, access: Access) -> Result<(), String> { let path = path.as_ref(); - let root = match access { - Access::Read => self.read.as_ref(), - Access::Write => self.write.as_ref(), + let roots = match access { + Access::Read => &self.read, + Access::Write => &self.write, }; - let Some(Root { resolved: folder, shown }) = root else { + if roots.is_empty() { return match access { Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {}", path.display())), Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {}", path.display())), }; - }; - if inside(&resolve(path)?, folder) { + } + let resolved = resolve(path)?; + if roots.iter().any(|r| inside(&resolved, &r.resolved)) { return Ok(()); } - let root = shown.display(); - match access { - Access::Read => Err(format!("automation path rejected: outside the read root {root}: {}", path.display())), - Access::Write => Err(format!("automation path rejected: outside the write root {root}: {}", path.display())), + let shown: Vec = roots.iter().map(|r| r.shown.display().to_string()).collect(); + match (shown.as_slice(), access) { + ([root], Access::Read) => Err(format!("automation path rejected: outside the read root {root}: {}", path.display())), + ([root], Access::Write) => Err(format!("automation path rejected: outside the write root {root}: {}", path.display())), + (_, Access::Read) => Err(format!("automation path rejected: outside the read roots {}: {}", shown.join(", "), path.display())), + (_, Access::Write) => Err(format!("automation path rejected: outside the write roots {}: {}", shown.join(", "), path.display())), } } } @@ -279,7 +295,7 @@ mod tests { } std::fs::write(base.join("in/a.designcraft"), "x").unwrap(); std::fs::write(base.join("outside/secret.designcraft"), "x").unwrap(); - let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("out"))).unwrap().unwrap(); + let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap().unwrap(); (base, roots) } @@ -339,18 +355,18 @@ mod tests { #[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(); + let e = AutomationRoots::new(&[&base.join("nope")], &[]).unwrap_err(); assert!(e.starts_with("cannot open the automation read root"), "{e}"); - let e = AutomationRoots::new(None, Some(&base.join("in/a.designcraft"))).unwrap_err(); + let e = AutomationRoots::new(&[], &[&base.join("in/a.designcraft")]).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()); + assert!(AutomationRoots::new(&[Path::new("")], &[]).unwrap_err().starts_with("cannot open the automation read root ``")); + assert!(AutomationRoots::new(&[], &[]).unwrap().is_none()); // One root alone grants only its own access. - let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); + let read_only = AutomationRoots::new(&[&base.join("in")], &[]).unwrap().unwrap(); let e = read_only.check(s(base.join("in/x.designcraft")), Access::Write).unwrap_err(); assert!(e.contains("write authority is absent"), "{e}"); let _ = std::fs::remove_dir_all(base); @@ -387,11 +403,125 @@ mod tests { assert_eq!(roots.check(s(base.join("in/alias/x.designcraft")), 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(); + let linked = AutomationRoots::new(&[&base.join("in-link")], &[]).unwrap().unwrap(); assert_eq!(linked.check(s(base.join("in/a.designcraft")), Access::Read), Ok(())); let _ = std::fs::remove_dir_all(base); } + /// `in` and `shared` (read roots), `out` and `scratch` (write roots) beside `outside`, the + /// siblings `in2` and `scratch2` whose names start like a root's, and a file in their parent. + /// The folder is returned resolved (`/var` is `/private/var` on macOS), as the roots show it, so + /// a path that passes only because it was resolved is the case being tested and nothing else. + fn several(name: &str) -> (PathBuf, Arc) { + let (base, _) = folders(name); + let base = std::fs::canonicalize(base).unwrap(); + for d in ["shared", "scratch", "scratch2"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + for f in ["shared/b.designcraft", "in2/c.designcraft", "parent.designcraft"] { + std::fs::write(base.join(f), "x").unwrap(); + } + let roots = AutomationRoots::new(&[&base.join("in"), &base.join("shared")], &[&base.join("out"), &base.join("scratch")]).unwrap().unwrap(); + (base, roots) + } + + /// #1552: several roots of a kind: a path inside any of them passes, one inside none is refused + /// naming them all, and read and write stay separate. + #[test] + fn several_roots_of_a_kind_each_grant_their_access() { + let (base, roots) = several("several"); + assert_eq!(roots.check(s(base.join("in/a.designcraft")), Access::Read), Ok(())); + assert_eq!(roots.check(s(base.join("shared/b.designcraft")), Access::Read), Ok(())); + assert_eq!(roots.check(s(base.join("out/x.png")), Access::Write), Ok(())); + assert_eq!(roots.check(s(base.join("scratch/new/x.png")), Access::Write), Ok(())); + let e = roots.check(s(base.join("outside/secret.designcraft")), Access::Read).unwrap_err(); + let listed = format!("outside the read roots {}, {}: ", s(base.join("in")), s(base.join("shared"))); + assert!(e.starts_with("automation path rejected: ") && e.contains(&listed), "{e}"); + assert!(roots.check(s(base.join("outside/x.png")), Access::Write).unwrap_err().contains("outside the write roots")); + // Two sibling roots don't make their parent a root. + assert!(roots.check(s(base.join("parent.designcraft")), Access::Read).unwrap_err().contains("outside the read roots")); + assert!(roots.check(s(base.clone()), Access::Read).is_err()); + assert!(roots.check(s(base.join("x.png")), Access::Write).unwrap_err().contains("outside the write roots")); + // Read and write stay separate: a read root is not a write root, nor the other way round. + assert!(roots.check(s(base.join("shared/b.designcraft")), Access::Write).unwrap_err().contains("outside the write roots")); + assert!(roots.check(s(base.join("in/x.png")), Access::Write).is_err()); + assert!(roots.check(s(base.join("scratch/x.png")), Access::Read).unwrap_err().contains("outside the read roots")); + assert!(roots.check(s(base.join("out")), Access::Read).is_err()); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn several_roots_compare_whole_folder_names() { + let (base, roots) = several("several-prefix"); + assert!(roots.check(s(base.join("in2/c.designcraft")), Access::Read).unwrap_err().contains("outside the read roots"), "in2 is not inside in"); + assert!(roots.check(format!("{}2/x.designcraft", s(base.join("shared"))), Access::Read).is_err()); + assert!( + roots.check(s(base.join("scratch2/x.png")), Access::Write).unwrap_err().contains("outside the write roots"), + "scratch2 is not inside scratch" + ); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn parent_traversal_between_several_roots() { + let (base, roots) = several("several-dotdot"); + let sep = std::path::MAIN_SEPARATOR; + let up = |root: &str, rest: &str| format!("{}{sep}..{sep}{rest}", s(base.join(root))); + // `..` out of one root is outside, also when it lands next to another root. + assert!(roots.check(up("shared", &format!("outside{sep}secret.designcraft")), Access::Read).unwrap_err().contains("outside the read roots")); + assert!(roots.check(up("shared", "parent.designcraft"), Access::Read).is_err()); + assert!(roots.check(up("scratch", &format!("outside{sep}x.png")), Access::Write).unwrap_err().contains("outside the write roots")); + // `..` from one root into another of the same kind stays inside. + assert_eq!(roots.check(up("shared", &format!("in{sep}a.designcraft")), Access::Read), Ok(())); + assert_eq!(roots.check(up("scratch", &format!("out{sep}x.png")), Access::Write), Ok(())); + // ...but not into a root of the other kind. + assert!(roots.check(up("scratch", &format!("in{sep}x.png")), Access::Write).unwrap_err().contains("outside the write roots")); + assert!(roots.check(up("shared", &format!("out{sep}x.png")), Access::Read).unwrap_err().contains("outside the read roots")); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn several_roots_are_each_checked_and_counted_once() { + let (base, _) = folders("several-open"); + // A missing folder among several is an error, wherever it stands. + for read in [[base.join("in"), base.join("nope")], [base.join("nope"), base.join("in")]] { + let e = AutomationRoots::new(&[&read[0], &read[1]], &[]).unwrap_err(); + assert!(e.starts_with("cannot open the automation read root") && e.contains("nope"), "{e}"); + } + let e = AutomationRoots::new(&[&base.join("in")], &[&base.join("out"), &base.join("in/a.designcraft")]).unwrap_err(); + assert!(e.starts_with("cannot open the automation write root"), "{e}"); + // A folder given twice (here once through `..`) counts once. + let twice = AutomationRoots::new(&[&base.join("in"), &base.join("in/sub/.."), &base.join("in")], &[]).unwrap().unwrap(); + let real = std::fs::canonicalize(&base).unwrap(); + assert_eq!(twice.describe(), format!("read {}; write none", s(real.join("in")))); + let e = twice.check(s(base.join("outside/x")), Access::Read).unwrap_err(); + assert!(e.contains("outside the read root ") && !e.contains("roots"), "{e}"); + let _ = std::fs::remove_dir_all(base); + } + + /// A link inside one root that leads into another root of the same kind stays inside; one that + /// leads out of all of them, or into a root of the other kind, is outside. + #[cfg(unix)] + #[test] + fn links_between_several_roots() { + let (base, roots) = several("several-links"); + let link = |target: &str, at: &str| std::os::unix::fs::symlink(base.join(target), base.join(at)).unwrap(); + link("shared/b.designcraft", "in/to-shared.designcraft"); + link("outside/secret.designcraft", "shared/leak.designcraft"); + link("", "shared/up"); + link("out", "in/to-out"); + link("outside", "scratch/away"); + link("in", "scratch/to-in"); + assert_eq!(roots.check(s(base.join("in/to-shared.designcraft")), Access::Read), Ok(())); + assert!(roots.check(s(base.join("shared/leak.designcraft")), Access::Read).unwrap_err().contains("outside the read roots")); + assert!(roots.check(s(base.join("shared/up/outside/secret.designcraft")), Access::Read).unwrap_err().contains("outside the read roots")); + assert!(roots.check(s(base.join("shared/up/parent.designcraft")), Access::Read).is_err()); + assert!(roots.check(s(base.join("in/to-out/x.png")), Access::Read).unwrap_err().contains("outside the read roots")); + assert!(roots.check(s(base.join("scratch/away/x.png")), Access::Write).unwrap_err().contains("outside the write roots")); + assert!(roots.check(s(base.join("scratch/to-in/x.png")), Access::Write).unwrap_err().contains("outside the write roots")); + let _ = std::fs::remove_dir_all(base); + } + #[cfg(windows)] #[test] fn windows_ignores_case_and_refuses_devices() { diff --git a/crates/engine/src/tests_roots.rs b/crates/engine/src/tests_roots.rs index 39ab5e57d..0f9b9654e 100644 --- a/crates/engine/src/tests_roots.rs +++ b/crates/engine/src/tests_roots.rs @@ -23,7 +23,7 @@ fn folders(name: &str) -> (PathBuf, Arc) { for d in ["in", "out", "outside"] { std::fs::create_dir_all(base.join(d)).unwrap(); } - let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("out"))).unwrap().unwrap(); + let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap().unwrap(); (base, roots) } diff --git a/crates/mcp/tests/it/automation_roots.rs b/crates/mcp/tests/it/automation_roots.rs index 871945920..8dcc3228d 100644 --- a/crates/mcp/tests/it/automation_roots.rs +++ b/crates/mcp/tests/it/automation_roots.rs @@ -51,7 +51,7 @@ fn confined(tag: &str, read: bool, write: bool) -> (Server, PathBuf) { std::fs::write(dir.join("tags.xml"), format!("

{text}

")).unwrap(); } let (in_dir, out_dir) = (base.join("in"), base.join("out")); - let roots = AutomationRoots::new(read.then_some(in_dir.as_path()), write.then_some(out_dir.as_path())).unwrap(); + let roots = AutomationRoots::new(read.then_some(in_dir.as_path()).as_slice(), write.then_some(out_dir.as_path()).as_slice()).unwrap(); let mut server = Server::new(Box::new(Headless::with_document().with_automation_roots(roots))); ok(&mut server, "new_document", json!({})); (server, base) @@ -339,7 +339,7 @@ fn without_roots_nothing_is_confined() { let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(&base).unwrap(); designcraft_file(&base.join("a.designcraft"), 3, "Anywhere"); - let mut server = Server::new(Box::new(Headless::with_document().with_automation_roots(AutomationRoots::new(None, None).unwrap()))); + let mut server = Server::new(Box::new(Headless::with_document().with_automation_roots(AutomationRoots::new(&[], &[]).unwrap()))); ok(&mut server, "open_document", json!({"path": s(&base.join("a.designcraft"))})); assert_eq!(pages(&mut server), 3); ok(&mut server, "save_document", json!({"path": s(&base.join("b.designcraft"))})); diff --git a/docs/mcp.md b/docs/mcp.md index 7cf8227da..432a31794 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -88,6 +88,8 @@ claude mcp add designcraft -- designcraft-cli mcp ```sh designcraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project/out +designcraft-cli mcp --automation-read-root /work/project --automation-read-root /work/shared-assets \ + --automation-write-root /work/project/out --automation-write-root /tmp/scratch ``` ```json @@ -98,16 +100,16 @@ designcraft-cli mcp --automation-read-root /work/project --automation-write-root The two flags (VectorCraft, PhotoCraft and the other Craft apps take the same ones, so one client config 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_document`, `file.open`, +- Every file a command reads must lie inside a **read root**: `open_document`, `file.open`, `file.openIdml`, `place_image` and `file.place` / `place.load` / `media.options` with a `path`, `links.relink`, `links.relinkFolder`, `color.loadProfile`, `swatch.load`, `library.open`, `book.open`, `data.source.select`, `data.merge` and `file.importXml` / `xml.loadDtd` with a `path`, and `file.recovery.list` / `file.recovery.open` with a `dir`. A DesignCraft document names more files than the agent does: linked images, data sources, book chapters, the `Document Fonts` folder beside a document, an IDML package's linked images and the files an image cell of a merge names. - Those are read through the same checks, so a path in a document that leads outside the read root + Those are read through the same checks, so a path in a document that leads outside the read roots reads as a file that isn't there. -- Every file a command writes must lie inside the **write root**: `save_document`, `export_png`, +- Every file a command writes must lie inside a **write root**: `save_document`, `export_png`, `render_page` with a `path`, `file.save`, `file.saveAs`, `file.saveACopy`, `file.exportPdf`, `file.exportEpub`, `file.exportFixedEpub`, `file.exportHtml`, `file.exportText`, `file.exportXml`, `file.exportIdml`, `file.printBooklet`, `snippet.export`, `swatch.save`, `library.new` and the @@ -115,21 +117,26 @@ config works across the suite) keep the agent to the folders you give it: `file.package`, `links.copyTo` and `file.recovery.save` / `file.recovery.open` with a `dir` (reopening removes the entries it read). `file.package` and `links.copyTo` check their folder before they create anything. -- 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. +- Each flag may be given more than once (#1552): a path inside any of the read roots may be read, + one inside any of the write roots written, so one session can read a project folder and a shared + assets folder, or write to an output folder and a scratch folder, without widening a root to + their common parent (which the roots don't grant). A folder given twice counts once. +- Read and write access are separate. Give the same folder to both flags for both. A kind 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, + file (or folder) link that leads out of the roots is outside them. 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 (writing through it would - create its target). The result is compared with the root by whole folder names: `/work2/x` is not + create its target). The result is compared with each root by whole folder names: `/work2/x` is not inside `/work`. On Windows case is ignored, UNC paths (`\\server\share\...`) are resolved like drive-letter ones, and device names (`CON`, `NUL`, `COM1`...) are refused. - A refused path is an ordinary tool error the agent can read and correct, for example - `automation path rejected: outside the write root /work/project/out: /etc/x.designcraft` or + `automation path rejected: outside the write root /work/project/out: /etc/x.designcraft` (with + several, `outside the write roots /work/project/out, /tmp/scratch: ...`) or `automation filesystem access is not granted: write authority is absent: /work/project/out/x.designcraft`. -- The roots must be existing folders; a missing one stops the server with an error. Each flag is - given once (`--flag ` or `--flag=`). +- The roots must be existing folders; a missing one stops the server with an error. Each flag takes + one folder per use (`--flag ` or `--flag=`) and may be used again for more. The flags confine the in-process server, so `--connect` together with them is an error: the server would otherwise talk to an app that isn't confined. DesignCraft's desktop app has no equivalent flags