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 and temporary child
  paths before create_dir_all, 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
  .cadcraft-tmp file would land beside the root, outside it.
- Save-style writers check their derived temporary path as well.
- 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 commit is contained in:
Nicholas Gower committed 2026-10-22 05:50:44 -07:00
1 parent c3f7b8cca2
commit 72961da7fd
9 files changed
+201 -48

No files matched your search

+5 -4
View File
@@ -77,10 +77,11 @@ image framing (png 2400x1600, svg, pdf; always model space):
opened drawing's view is its extents plus a 10% margin).
mcp file access (headless only):
--automation-read-root DIR the only folder the agent's commands may read from
--automation-write-root DIR the only folder they may write to
(give the same folder twice for both; a root left out grants
none of its access; without either, nothing is confined)";
--automation-read-root DIR the only folder the agent's commands may read from (reads are
also allowed under the write root)
--automation-write-root DIR the only folder they may write to, never the folder itself
(give the same folder twice for both; a read root alone allows
no writes; without either, nothing is confined)";
/// What part of model space an image export shows.
#[derive(Clone, Copy, Debug, PartialEq)]
+77 -9
View File
@@ -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<Tool>) {
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<Tool>) {
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<Tool>) {
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<String> =
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<String> =
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<String> = 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);
}
+1
View File
@@ -81,6 +81,7 @@ fn write_file(cmd: &str, path: &str, bytes: &[u8]) -> Result<()> {
{
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
let tmp = format!("{path}.cadcraft-tmp");
crate::file_access::check_write(&tmp).map_err(|e| bad(cmd, e))?;
std::fs::write(&tmp, bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
std::fs::rename(&tmp, path).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
Ok(())
+1
View File
@@ -408,6 +408,7 @@ fn store(path: &str, bytes: &[u8]) -> Result<()> {
{
crate::file_access::check_write(path).map_err(|e| bad("save", e))?;
let tmp = format!("{path}.cadcraft-tmp");
crate::file_access::check_write(&tmp).map_err(|e| bad("save", e))?;
std::fs::write(&tmp, bytes).map_err(|e| bad("save", format!("{path}: {e}")))?;
std::fs::rename(&tmp, path).map_err(|e| bad("save", format!("{path}: {e}")))?;
Ok(())
+1
View File
@@ -828,6 +828,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
let path = _path;
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
let tmp = format!("{path}.cadcraft-tmp");
crate::file_access::check_write(&tmp).map_err(|e| bad(cmd, e))?;
std::fs::write(&tmp, &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
std::fs::rename(&tmp, path).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
Ok(json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages }))
@@ -335,6 +335,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
{
crate::file_access::check_write(_path).map_err(|e| bad(cmd, e))?;
let tmp = format!("{_path}.cadcraft-tmp");
crate::file_access::check_write(&tmp).map_err(|e| bad(cmd, e))?;
std::fs::write(&tmp, text.as_bytes()).map_err(|e| bad(cmd, format!("{_path}: {e}")))?;
std::fs::rename(&tmp, _path).map_err(|e| bad(cmd, format!("{_path}: {e}")))?;
Ok(json!({ "name": name, "path": _path, "bytes": text.len() }))
+35 -4
View File
@@ -86,9 +86,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()),
@@ -101,6 +119,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"));
@@ -109,12 +128,20 @@ impl PlotterStore {
},
write: |n, t| {
let p = file(n)?;
std::fs::create_dir_all(dir()?).map_err(|e| e.to_string())?;
let d = dir()?;
let tmp = p.with_extension("json.cadcraft-tmp");
// Check both child paths before creating the folder they live in.
check_write(&p)?;
check_write(&tmp)?;
std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
std::fs::write(&tmp, t).map_err(|e| format!("{n}: {e}"))?;
std::fs::rename(&tmp, &p).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}"))
},
}
}
}
@@ -522,7 +549,11 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
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::<Vec<_>>() })),
"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::<Vec<_>>() }))
}
"get" => {
let n = device_name(cmd, p)?;
let c = find_device(&n).ok_or_else(|| unknown_device(cmd, &n))?;
+65 -20
View File
@@ -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}")),
};
};
if inside(&resolve(path)?, folder) {
return Ok(());
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 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}")),
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(&target, folder) {
return Err(format!("automation path rejected: outside the write root {}: {path}", shown.display()));
}
// A write to the root itself would put its `.cadcraft-tmp` 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);
}
+15 -11
View File
@@ -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 <dir>` or `--flag=<dir>`).