From 49eda850831813866b456e6119bf85136dae4904 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:24:18 -0800 Subject: [PATCH 1/6] craft-mcp: Roots confines tool file paths to read and write roots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit roots::Roots holds the folders an MCP server's tools may read from and write to. Roots::check makes a path absolute, follows its links (for a missing path, those of its nearest existing folder), and returns it only when it lies inside a root of the requested kind. It refuses `..` below a missing folder and links that lead nowhere. On Windows it refuses device names such as CON, NUL, COM1 and LPT¹, `:` in a name, names ending in a dot or a space, `\\.\` paths, and `\\?\` paths other than plain drive and UNC paths, so a path that check returned can be checked again. Names with no text form are kept as they are. Roots::required refuses to build roots without both kinds. --- crates/mcp/README.md | 9 + crates/mcp/src/lib.rs | 2 + crates/mcp/src/roots.rs | 500 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 511 insertions(+) create mode 100644 crates/mcp/src/roots.rs diff --git a/crates/mcp/README.md b/crates/mcp/README.md index e84a1a40c5..e4dc516f7a 100644 --- a/crates/mcp/README.md +++ b/crates/mcp/README.md @@ -14,4 +14,13 @@ a different version. An initialized notification moves the session to `Ready`. This crate does not enforce every MCP lifecycle or capability rule; applications must validate any additional requirements they depend on. +`roots::Roots` confines the file paths in tool arguments to read and write roots. +`Roots::check` resolves a path, following links, and returns it only when it lies +inside a root of the requested kind. On Windows it also refuses device names, +alternate data streams, names that end in a dot or a space, `\\.\` paths, and `\\?\` +paths other than plain drive and UNC paths such as those `check` returns. +`Roots::required` refuses to build roots without both kinds. A path is checked +before it is opened, so another program that replaces a folder with a link between +the two steps can still reach outside the roots. + See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle). diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index 6ca888fc06..8259050f74 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -8,6 +8,8 @@ use craft_jsonrpc::{Request, RpcError}; use serde_json::{Value, json}; +pub mod roots; + pub const PROTOCOL_VERSION: &str = "2025-03-26"; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] diff --git a/crates/mcp/src/roots.rs b/crates/mcp/src/roots.rs new file mode 100644 index 0000000000..b8b18b42f1 --- /dev/null +++ b/crates/mcp/src/roots.rs @@ -0,0 +1,500 @@ +//! The folders an MCP server's tools may read from and write to. +//! +//! [`Roots`] holds read roots and write roots. A path inside any read root may be read, and a path +//! inside any write root may be written. A kind of access with no root of its own is not granted. +//! [`Roots::required`] refuses to build roots unless both kinds are given, for entry points that +//! must not start without them. +//! +//! [`Roots::check`] checks a path like this: +//! +//! - It is made absolute against the working directory, then its links are followed. For a path +//! that does not exist yet, the links of its nearest existing folder are followed and the rest +//! must be plain names: `..` below a folder that does not exist is refused, and so is a link +//! that leads nowhere. +//! - The result must be a root or lie inside one, compared folder name by folder name, so `/work2` +//! is not inside `/work`. Following the links gives existing names as the file system stores +//! them, so a path typed in another case still matches on a file system that ignores case. +//! - On Windows these are refused: device names (`CON`, `NUL`, `COM1`, `LPT¹` and the like, also +//! with an extension), a `:` after the drive, a file or folder name that ends in a dot or a +//! space, a path that starts with `\\.\`, and one that starts with `\\?\` unless it is a drive +//! or UNC path with no `/` and no empty, `.` or `..` name, such as a path [`Roots::check`] +//! returned. The names follow +//! . +//! +//! A path is checked and then opened. Another program that swaps a folder for a link between the +//! two steps can still reach outside the roots: the roots confine the client's tool arguments, not +//! other programs on the computer. + +use std::ffi::OsString; +use std::fmt; +use std::path::{Component, Path, PathBuf, Prefix}; + +/// Reading a file or writing one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Access { + Read, + Write, +} + +impl fmt::Display for Access { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Access::Read => "read", + Access::Write => "write", + }) + } +} + +impl Access { + fn verb(self) -> &'static str { + match self { + Access::Read => "read", + Access::Write => "written", + } + } +} + +/// Why a path may not be used, or a root could not be set up. `BadRoot` is a root that is not an +/// existing folder, `NoRoot` a kind [`Roots::required`] was given no root for, and `NotGranted` a +/// check for a kind that has no root. +#[derive(Debug, PartialEq, Eq)] +pub enum AccessError { + BadRoot { access: Access, path: PathBuf, reason: String }, + NoRoot { access: Access }, + NotGranted { access: Access, path: PathBuf }, + Outside { access: Access, path: PathBuf, roots: String }, + Empty, + Device { path: PathBuf }, + Stream { path: PathBuf }, + TrailingDotOrSpace { path: PathBuf }, + Verbatim { path: PathBuf }, + ParentOfMissing { path: PathBuf }, + BrokenLink { path: PathBuf }, + Unresolved { path: PathBuf, reason: String }, +} + +impl fmt::Display for AccessError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + AccessError::BadRoot { access, path, reason } => write!(f, "the {access} root `{}` can't be used: {reason}", path.display()), + AccessError::NoRoot { access } => write!(f, "no {access} root was given"), + AccessError::NotGranted { access, path } => { + write!(f, "files can't be {}: no {access} root was given: {}", access.verb(), path.display()) + } + AccessError::Outside { access, path, roots } => write!(f, "{} is outside the {access} roots ({roots})", path.display()), + AccessError::Empty => f.write_str("an empty path names no file"), + AccessError::Device { path } => write!(f, "{} names a device, not a file", path.display()), + AccessError::Stream { path } => write!(f, "{} has a `:` in a file or folder name", path.display()), + AccessError::TrailingDotOrSpace { path } => write!(f, "{} has a file or folder name that ends in a dot or a space", path.display()), + AccessError::Verbatim { path } => write!(f, r"{} starts with `\\?\` or `\\.\`; give the path without that prefix", path.display()), + AccessError::ParentOfMissing { path } => write!(f, "{} goes up with `..` below a folder that does not exist", path.display()), + AccessError::BrokenLink { path } => write!(f, "{} is a link to something that does not exist", path.display()), + AccessError::Unresolved { path, reason } => write!(f, "{} could not be resolved: {reason}", path.display()), + } + } +} + +impl std::error::Error for AccessError {} + +/// The read and write roots, each made absolute with its links followed. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Roots { + read: Vec, + write: Vec, +} + +impl Roots { + /// Roots from the folders given, which must exist. A folder given twice counts once. Either + /// list may be empty; that kind of access is then not granted. + pub fn new(read: &[PathBuf], write: &[PathBuf]) -> Result { + Ok(Roots { read: open_all(read, Access::Read)?, write: open_all(write, Access::Write)? }) + } + + /// [`Roots::new`], refusing roots that leave out either kind. + pub fn required(read: &[PathBuf], write: &[PathBuf]) -> Result { + if read.is_empty() { + return Err(AccessError::NoRoot { access: Access::Read }); + } + if write.is_empty() { + return Err(AccessError::NoRoot { access: Access::Write }); + } + Roots::new(read, write) + } + + /// The read roots, absolute with their links followed. + pub fn read(&self) -> &[PathBuf] { + &self.read + } + + /// The write roots, absolute with their links followed. + pub fn write(&self) -> &[PathBuf] { + &self.write + } + + /// Whether neither kind of root was given. + pub fn is_empty(&self) -> bool { + self.read.is_empty() && self.write.is_empty() + } + + /// `path` resolved, when it may be used for `access`; otherwise why not. + pub fn check(&self, path: &Path, access: Access) -> Result { + let roots = match access { + Access::Read => &self.read, + Access::Write => &self.write, + }; + if roots.is_empty() { + return Err(AccessError::NotGranted { access, path: path.to_path_buf() }); + } + let resolved = resolve(path)?; + if roots.iter().any(|r| inside(&resolved, r)) { + return Ok(resolved); + } + Err(AccessError::Outside { access, path: path.to_path_buf(), roots: list(roots) }) + } + + /// One line naming the roots, for server instructions and logs. + pub fn describe(&self) -> String { + let list = |roots: &[PathBuf]| if roots.is_empty() { "none".to_owned() } else { list(roots) }; + format!("read roots {}; write roots {}", list(&self.read), list(&self.write)) + } +} + +fn list(roots: &[PathBuf]) -> String { + roots.iter().map(|r| display_path(r).display().to_string()).collect::>().join(", ") +} + +fn open_all(paths: &[PathBuf], access: Access) -> Result, AccessError> { + let mut out: Vec = Vec::with_capacity(paths.len()); + for p in paths { + let bad = |reason: String| AccessError::BadRoot { access, path: p.clone(), reason }; + if p.as_os_str().is_empty() { + return Err(bad("an empty path names no folder".into())); + } + let resolved = std::fs::canonicalize(p).map_err(|e| bad(e.to_string()))?; + if !resolved.is_dir() { + return Err(bad("it is not a folder".into())); + } + if !out.iter().any(|r| same_path(r, &resolved)) { + out.push(resolved); + } + } + Ok(out) +} + +/// `path` without the `\\?\` prefix of Windows' canonical paths, for messages and logs. On Windows +/// a name that has no text form is shown with U+FFFD in its place. Other paths are returned +/// unchanged. +pub fn display_path(path: &Path) -> PathBuf { + if !cfg!(windows) { + return path.to_path_buf(); + } + let text = path.to_string_lossy(); + if let Some(rest) = text.strip_prefix(r"\\?\UNC\") { + return PathBuf::from(format!(r"\\{rest}")); + } + text.strip_prefix(r"\\?\").map_or_else(|| path.to_path_buf(), PathBuf::from) +} + +/// `path` made absolute with its links followed; for a path that does not exist, its nearest +/// existing folder's links followed and the remaining names added. +fn resolve(path: &Path) -> Result { + if path.as_os_str().is_empty() { + return Err(AccessError::Empty); + } + let plain; + let path = if cfg!(windows) { + plain = without_verbatim_prefix(path)?; + check_windows_names(&plain)?; + plain.as_path() + } else { + path + }; + // On Windows, `std::path::absolute` removes each `..` and the name before it from the text, so + // a `..` that follows a missing folder is refused here, before that happens. + let mut before = PathBuf::new(); + for c in path.components() { + if c == Component::ParentDir + && !before.as_os_str().is_empty() + && matches!(std::fs::symlink_metadata(&before), Err(e) if e.kind() == std::io::ErrorKind::NotFound) + { + return Err(AccessError::ParentOfMissing { path: path.to_path_buf() }); + } + before.push(c); + } + let unresolved = |reason: String| AccessError::Unresolved { path: path.to_path_buf(), reason }; + let absolute = std::path::absolute(path).map_err(|e| unresolved(e.to_string()))?; + // Names below the nearest existing folder, the last one first. + let mut missing: Vec = Vec::new(); + 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(AccessError::BrokenLink { path: path.to_path_buf() }), + Ok(_) => return Err(unresolved(e.to_string())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(unresolved(e.to_string())), + }, + } + match (at.components().next_back(), at.parent()) { + (Some(Component::Normal(name)), Some(parent)) => { + missing.push(name.to_os_string()); + at = parent; + } + (Some(Component::ParentDir), _) => return Err(AccessError::ParentOfMissing { path: path.to_path_buf() }), + _ => return Err(unresolved("no part of it exists".into())), + } + } +} + +/// A `\\?\C:\` or `\\?\UNC\` path, such as one [`Roots::check`] returned, without its prefix, when +/// every name after the prefix is one Windows would parse the same way without it: no `/`, and no +/// empty, `.` or `..` name. Other paths are returned unchanged. The names are copied as they are, +/// without a conversion to text. +fn without_verbatim_prefix(path: &Path) -> Result { + let Some(Component::Prefix(prefix)) = path.components().next() else { + return Ok(path.to_path_buf()); + }; + let mut plain = match prefix.kind() { + Prefix::VerbatimDisk(drive) => PathBuf::from(format!("{}:\\", char::from(drive))), + Prefix::VerbatimUNC(server, share) => { + let mut unc = OsString::from(r"\\"); + unc.push(server); + unc.push(r"\"); + unc.push(share); + PathBuf::from(unc) + } + _ => return Ok(path.to_path_buf()), + }; + let refused = || AccessError::Verbatim { path: path.to_path_buf() }; + let bytes = path.as_os_str().as_encoded_bytes(); + let rest = bytes.get(prefix.as_os_str().len()..).ok_or_else(refused)?; + // `\\?\C:foo` names `foo` in the drive's current folder, not `C:\foo`. + let disk = matches!(prefix.kind(), Prefix::VerbatimDisk(_)); + let rest = match rest.strip_prefix(b"\\") { + Some(rest) => rest, + None if rest.is_empty() && !disk => rest, + None => return Err(refused()), + }; + if rest.contains(&b'/') || (!rest.is_empty() && rest.split(|&b| b == b'\\').any(|name| matches!(name, b"" | b"." | b".."))) { + return Err(refused()); + } + for c in path.components().skip(1) { + match c { + Component::RootDir => {} + Component::Normal(name) => plain.push(name), + _ => return Err(refused()), + } + } + Ok(plain) +} + +/// The Windows name rules from the module documentation. +fn check_windows_names(path: &Path) -> Result<(), AccessError> { + for c in path.components() { + match c { + // These prefixes turn off Windows' own name parsing for the rest of the path. + Component::Prefix(p) + if matches!(p.kind(), Prefix::Verbatim(_) | Prefix::VerbatimUNC(..) | Prefix::VerbatimDisk(_) | Prefix::DeviceNS(_)) => + { + return Err(AccessError::Verbatim { path: path.to_path_buf() }); + } + Component::Normal(name) => { + let name = name.to_string_lossy(); + if is_device_name(&name) { + return Err(AccessError::Device { path: path.to_path_buf() }); + } + if name.contains(':') { + return Err(AccessError::Stream { path: path.to_path_buf() }); + } + if name.ends_with(['.', ' ']) { + return Err(AccessError::TrailingDotOrSpace { path: path.to_path_buf() }); + } + } + _ => {} + } + } + Ok(()) +} + +/// Whether the resolved `path` is `root` or lies inside it, folder name by folder name. Both come +/// from `canonicalize`, which gives each existing name as the file system stores it, so names are +/// compared exactly. Folding case would make two folders equal in a Windows folder set to be +/// case-sensitive, or two names that differ beyond ASCII case. +fn inside(path: &Path, root: &Path) -> bool { + let mut parts = path.components(); + root.components().all(|r| parts.next() == Some(r)) +} + +fn same_path(a: &Path, b: &Path) -> bool { + a.components().count() == b.components().count() && inside(a, b) +} + +/// A Windows device name (`CON`, `NUL`, `COM1`, `LPT¹` and the like, also with an extension). +fn is_device_name(name: &str) -> bool { + let stem = name.split('.').next().unwrap_or(name).trim_end_matches(' ').to_ascii_uppercase(); + let numbered = |prefix: &str| { + stem.strip_prefix(prefix).is_some_and(|n| { + let mut chars = n.chars(); + chars.next().is_some_and(|c| matches!(c, '1'..='9' | '¹' | '²' | '³')) && chars.next().is_none() + }) + }; + matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A fresh folder holding `in` (the read root), `out` (the write root), `outside` and `in2`. + fn folders(tag: &str) -> (PathBuf, Roots) { + let base = std::env::temp_dir().join(format!("craft-mcp-roots-{tag}-{}", 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/show.json"), "{}").unwrap(); + std::fs::write(base.join("outside/secret.json"), "{}").unwrap(); + let roots = Roots::new(&[base.join("in")], &[base.join("out")]).unwrap(); + (base, roots) + } + + #[test] + fn paths_inside_a_root_pass_and_others_are_refused() { + let (base, roots) = folders("inside"); + assert!(roots.check(&base.join("in/show.json"), Access::Read).is_ok()); + assert!(roots.check(&base.join("in"), Access::Read).is_ok(), "the root itself"); + assert!(roots.check(&base.join("in/sub/new.json"), Access::Read).is_ok(), "a missing file is checked by its folder"); + assert!(roots.check(&base.join("out/new/deeper/x.mkv"), Access::Write).is_ok(), "and by its nearest existing folder"); + let e = roots.check(&base.join("outside/secret.json"), Access::Read).unwrap_err(); + assert!(matches!(e, AccessError::Outside { access: Access::Read, .. }), "{e}"); + assert!(matches!(roots.check(&base.join("in/show.json"), Access::Write), Err(AccessError::Outside { .. }))); + assert!(matches!(roots.check(&base.join("out/x.json"), Access::Read), Err(AccessError::Outside { .. }))); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn a_sibling_with_the_same_prefix_is_outside() { + let (base, roots) = folders("prefix"); + assert!(roots.check(&base.join("in2/x.json"), Access::Read).is_err()); + let text = format!("{}2{}x.json", base.join("in").display(), std::path::MAIN_SEPARATOR); + assert!(roots.check(Path::new(&text), Access::Read).is_err()); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn parent_steps_are_resolved_or_refused() { + let (base, roots) = folders("dotdot"); + let up = base.join("in").join("..").join("outside").join("secret.json"); + assert!(matches!(roots.check(&up, Access::Read), Err(AccessError::Outside { .. })), "an existing path is resolved first"); + let back_in = base.join("in").join("sub").join("..").join("show.json"); + assert!(roots.check(&back_in, Access::Read).is_ok(), "`..` that stays inside is allowed"); + let below_missing = base.join("in").join("nothing").join("..").join("..").join("outside").join("secret.json"); + assert!(matches!(roots.check(&below_missing, Access::Read), Err(AccessError::ParentOfMissing { .. }))); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn a_kind_of_access_without_a_root_is_not_granted() { + let (base, _) = folders("one-kind"); + let roots = Roots::new(&[base.join("in")], &[]).unwrap(); + let e = roots.check(&base.join("in/show.json"), Access::Write).unwrap_err(); + assert!(matches!(e, AccessError::NotGranted { access: Access::Write, .. }), "{e}"); + assert!(roots.describe().contains("write roots none"), "{}", roots.describe()); + assert_eq!(Roots::required(&[base.join("in")], &[]), Err(AccessError::NoRoot { access: Access::Write })); + assert_eq!(Roots::required(&[], &[base.join("out")]), Err(AccessError::NoRoot { access: Access::Read })); + assert!(Roots::required(&[base.join("in")], &[base.join("out")]).is_ok()); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn several_roots_of_one_kind_each_grant_access_and_repeats_count_once() { + let (base, _) = folders("several"); + let roots = Roots::new(&[base.join("in"), base.join("in2"), base.join("in")], &[]).unwrap(); + assert_eq!(roots.read().len(), 2); + assert!(roots.check(&base.join("in2/x.json"), Access::Read).is_ok()); + assert!(roots.check(&base.join("in/show.json"), Access::Read).is_ok()); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn a_root_must_be_an_existing_folder() { + let (base, _) = folders("bad-root"); + assert!(matches!(Roots::new(&[base.join("missing")], &[]), Err(AccessError::BadRoot { .. }))); + assert!(matches!(Roots::new(&[], &[base.join("in/show.json")]), Err(AccessError::BadRoot { .. }))); + assert!(matches!(Roots::new(&[PathBuf::new()], &[]), Err(AccessError::BadRoot { .. }))); + assert!(matches!(Roots::new(&[base.join("in")], &[]).map(|r| r.check(Path::new(""), Access::Read)), Ok(Err(AccessError::Empty)))); + let _ = std::fs::remove_dir_all(base); + } + + #[cfg(unix)] + #[test] + fn links_that_lead_out_of_a_root_are_outside() { + let (base, roots) = folders("links"); + std::os::unix::fs::symlink(base.join("outside"), base.join("in/escape")).unwrap(); + std::os::unix::fs::symlink(base.join("outside/none"), base.join("in/dangling")).unwrap(); + assert!(matches!(roots.check(&base.join("in/escape/secret.json"), Access::Read), Err(AccessError::Outside { .. }))); + assert!(matches!(roots.check(&base.join("in/dangling"), Access::Read), Err(AccessError::BrokenLink { .. }))); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn device_names_are_recognized() { + for name in ["CON", "nul", "COM1", "lpt9.txt", "AUX ", "COM¹", "lpt³.log", "NUL.tar.gz"] { + assert!(is_device_name(name), "{name}"); + } + for name in ["COM0", "COM10", "COM¹1", "console", "show.json"] { + assert!(!is_device_name(name), "{name}"); + } + } + + #[cfg(windows)] + #[test] + fn verbatim_paths_and_windows_name_rules_are_refused() { + let (base, roots) = folders("verbatim"); + let inside = base.join("in/show.json"); + let checked = roots.check(&inside, Access::Read).unwrap(); + assert_eq!(roots.check(&checked, Access::Read).as_ref(), Ok(&checked), "a checked path checks again"); + assert!(roots.check(&roots.read()[0].join("new.json"), Access::Read).is_ok(), "a name joined to a root"); + // A folder name with an unpaired UTF-16 surrogate, which has no text form. + let odd: OsString = std::os::windows::ffi::OsStringExt::from_wide(&[u16::from(b'a'), 0xD800]); + std::fs::create_dir_all(base.join("in").join(&odd)).unwrap(); + let checked = roots.check(&base.join("in").join(&odd).join("x.json"), Access::Read).unwrap(); + assert_eq!(roots.check(&checked, Access::Read).as_ref(), Ok(&checked), "names are kept as they are"); + let verbatim = |p: &Path| PathBuf::from(format!(r"\\?\{}", std::path::absolute(p).unwrap().display())); + assert!(roots.check(&verbatim(&inside), Access::Read).is_ok()); + for escape in [r"in\..\outside\secret.json", r"in\.\show.json", r"in\\show.json", r"in/show.json"] { + let p = PathBuf::from(format!(r"{}\{escape}", verbatim(&base).display())); + assert!(matches!(roots.check(&p, Access::Read), Err(AccessError::Verbatim { .. })), "{escape}"); + } + let trailing = PathBuf::from(format!(r"{}\in\show.json.", verbatim(&base).display())); + assert!(matches!(roots.check(&trailing, Access::Read), Err(AccessError::TrailingDotOrSpace { .. }))); + let drive = std::path::absolute(&inside).unwrap().to_string_lossy().chars().next().unwrap(); + for relative in [format!(r"\\?\{drive}:show.json"), format!(r"\\?\{drive}:")] { + assert!(matches!(roots.check(Path::new(&relative), Access::Read), Err(AccessError::Verbatim { .. })), "{relative}"); + } + let root = PathBuf::from(r"\\?\GLOBALROOT\Device\HarddiskVolume1\x.json"); + assert!(matches!(roots.check(&root, Access::Read), Err(AccessError::Verbatim { .. }))); + let device = PathBuf::from(format!(r"\\.\{}", std::path::absolute(&inside).unwrap().display())); + assert!(matches!(roots.check(&device, Access::Read), Err(AccessError::Verbatim { .. }))); + for name in ["show.json.", "show.json ", "sub./x.json", "sub /x.json"] { + let e = roots.check(&base.join("in").join(name), Access::Read).unwrap_err(); + assert!(matches!(e, AccessError::TrailingDotOrSpace { .. }), "{name}: {e}"); + } + assert!(matches!(roots.check(&base.join("in/show.json:secret"), Access::Read), Err(AccessError::Stream { .. }))); + assert!(matches!(roots.check(&base.join("in/COM¹"), Access::Write), Err(AccessError::Device { .. }))); + assert!(roots.check(&base.join("IN").join("SHOW.JSON"), Access::Read).is_ok(), "a path typed in another case"); + assert!(roots.check(&base.join("IN").join("new.json"), Access::Read).is_ok(), "and a missing file below it"); + // `İ` lowercases to `i` and a combining dot, which names a different folder. + std::fs::create_dir_all(base.join("\u{130}")).unwrap(); + std::fs::create_dir_all(base.join("i\u{307}")).unwrap(); + let dotted = Roots::new(&[base.join("\u{130}")], &[]).unwrap(); + assert!(matches!(dotted.check(&base.join("i\u{307}").join("x.json"), Access::Read), Err(AccessError::Outside { .. }))); + assert!(!display_path(&roots.read()[0]).to_string_lossy().starts_with(r"\\?\")); + assert!(roots.check(&inside, Access::Read).is_ok()); + let _ = std::fs::remove_dir_all(base); + } +} From 7ab5574f95a7b90f357454492ab9370f5aec3726 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:49:35 -0800 Subject: [PATCH 2/6] craft-mcp: Roots applies the Windows name rules to resolved paths too A link or junction can lead to a folder whose name the Windows rules refuse, such as one that ends in a dot. Roots::check now checks the path it returns, with its links followed, against the same rules, so a path it returns passes check again. Roots::new refuses a root whose resolved path breaks them, instead of accepting a root under which every path would be refused. --- crates/mcp/README.md | 3 ++- crates/mcp/src/roots.rs | 53 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/crates/mcp/README.md b/crates/mcp/README.md index e4dc516f7a..b67eda0827 100644 --- a/crates/mcp/README.md +++ b/crates/mcp/README.md @@ -16,7 +16,8 @@ must validate any additional requirements they depend on. `roots::Roots` confines the file paths in tool arguments to read and write roots. `Roots::check` resolves a path, following links, and returns it only when it lies -inside a root of the requested kind. On Windows it also refuses device names, +inside a root of the requested kind. On Windows it also refuses, in the path as +given and in the path its links lead to, device names, alternate data streams, names that end in a dot or a space, `\\.\` paths, and `\\?\` paths other than plain drive and UNC paths such as those `check` returns. `Roots::required` refuses to build roots without both kinds. A path is checked diff --git a/crates/mcp/src/roots.rs b/crates/mcp/src/roots.rs index b8b18b42f1..7e2ef1642d 100644 --- a/crates/mcp/src/roots.rs +++ b/crates/mcp/src/roots.rs @@ -14,11 +14,11 @@ //! - The result must be a root or lie inside one, compared folder name by folder name, so `/work2` //! is not inside `/work`. Following the links gives existing names as the file system stores //! them, so a path typed in another case still matches on a file system that ignores case. -//! - On Windows these are refused: device names (`CON`, `NUL`, `COM1`, `LPT¹` and the like, also -//! with an extension), a `:` after the drive, a file or folder name that ends in a dot or a -//! space, a path that starts with `\\.\`, and one that starts with `\\?\` unless it is a drive -//! or UNC path with no `/` and no empty, `.` or `..` name, such as a path [`Roots::check`] -//! returned. The names follow +//! - On Windows these are refused, in the path as given and again in the path its links lead to: +//! device names (`CON`, `NUL`, `COM1`, `LPT¹` and the like, also with an extension), a `:` +//! after the drive, a file or folder name that ends in a dot or a space, a path that starts +//! with `\\.\`, and one that starts with `\\?\` unless it is a drive or UNC path with no `/` +//! and no empty, `.` or `..` name, such as a path [`Roots::check`] returned. The names follow //! . //! //! A path is checked and then opened. Another program that swaps a folder for a link between the @@ -105,7 +105,8 @@ pub struct Roots { impl Roots { /// Roots from the folders given, which must exist. A folder given twice counts once. Either - /// list may be empty; that kind of access is then not granted. + /// list may be empty; that kind of access is then not granted. On Windows a folder whose path, + /// with its links followed, breaks the name rules in the module documentation is refused. pub fn new(read: &[PathBuf], write: &[PathBuf]) -> Result { Ok(Roots { read: open_all(read, Access::Read)?, write: open_all(write, Access::Write)? }) } @@ -174,6 +175,9 @@ fn open_all(paths: &[PathBuf], access: Access) -> Result, AccessErr if !resolved.is_dir() { return Err(bad("it is not a folder".into())); } + if cfg!(windows) { + check_resolved_names(&resolved).map_err(|e| bad(e.to_string()))?; + } if !out.iter().any(|r| same_path(r, &resolved)) { out.push(resolved); } @@ -230,6 +234,9 @@ fn resolve(path: &Path) -> Result { match std::fs::canonicalize(at) { Ok(mut found) => { found.extend(missing.iter().rev()); + if cfg!(windows) { + check_resolved_names(&found)?; + } return Ok(found); } Err(e) => match std::fs::symlink_metadata(at) { @@ -292,6 +299,12 @@ fn without_verbatim_prefix(path: &Path) -> Result { Ok(plain) } +/// The Windows name rules applied to a path with its links followed, so a link or junction to a +/// folder whose name the rules refuse is refused too. +fn check_resolved_names(found: &Path) -> Result<(), AccessError> { + check_windows_names(&without_verbatim_prefix(found)?) +} + /// The Windows name rules from the module documentation. fn check_windows_names(path: &Path) -> Result<(), AccessError> { for c in path.components() { @@ -497,4 +510,32 @@ mod tests { assert!(roots.check(&inside, Access::Read).is_ok()); let _ = std::fs::remove_dir_all(base); } + + /// A link or junction can lead to a folder whose name the Windows rules refuse; `canonicalize` + /// then returns that name. Making such a link needs rights the test may not have, so the check + /// runs on paths in the form `canonicalize` returns. + #[cfg(windows)] + #[test] + fn resolved_names_follow_the_windows_name_rules() { + for ok in [r"\\?\C:\work\actual\x.txt", r"\\?\UNC\server\share\work\x.txt", r"\\?\UNC\server\share"] { + assert_eq!(check_resolved_names(Path::new(ok)), Ok(()), "{ok}"); + } + let refused = |p: &str| check_resolved_names(Path::new(p)).unwrap_err(); + assert!(matches!(refused(r"\\?\C:\work\actual.\x.txt"), AccessError::TrailingDotOrSpace { .. })); + assert!(matches!(refused(r"\\?\C:\work\actual \x.txt"), AccessError::TrailingDotOrSpace { .. })); + assert!(matches!(refused(r"\\?\C:\work\CON\x.txt"), AccessError::Device { .. })); + assert!(matches!(refused(r"\\?\UNC\server\share\nul.txt"), AccessError::Device { .. })); + assert!(matches!(refused(r"\\?\Volume{00000000-0000-0000-0000-000000000000}\x.txt"), AccessError::Verbatim { .. })); + } + + #[cfg(windows)] + #[test] + fn a_root_whose_resolved_name_the_windows_rules_refuse_is_bad() { + let (base, _) = folders("resolved-root"); + let trailing = PathBuf::from(format!(r"\\?\{}\trailing.", std::path::absolute(&base).unwrap().display())); + std::fs::create_dir_all(&trailing).unwrap(); + let e = Roots::new(&[trailing], &[]).unwrap_err(); + assert!(matches!(e, AccessError::BadRoot { access: Access::Read, .. }), "{e}"); + let _ = std::fs::remove_dir_all(base); + } } From 4b17bf277dbf0e1cef7df764f483a7fe28cf3c92 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:39:44 -0800 Subject: [PATCH 3/6] craft-mcp: Roots refuses network shares outside the roots before resolving On Windows, Roots::check now reads the path's text before any file system call. A path on a network share (\server\share or \?\UNC\server\share, also after a relative path is made absolute) is refused unless a root of the requested kind is on the same server and share, so a refused path does not open a connection to another computer. Paths that start with \??\ are refused like \.\ paths, and roots are checked against the name rules before they are opened. --- crates/mcp/README.md | 18 ++++--- crates/mcp/src/roots.rs | 105 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 112 insertions(+), 11 deletions(-) diff --git a/crates/mcp/README.md b/crates/mcp/README.md index b67eda0827..3b82881125 100644 --- a/crates/mcp/README.md +++ b/crates/mcp/README.md @@ -17,11 +17,17 @@ must validate any additional requirements they depend on. `roots::Roots` confines the file paths in tool arguments to read and write roots. `Roots::check` resolves a path, following links, and returns it only when it lies inside a root of the requested kind. On Windows it also refuses, in the path as -given and in the path its links lead to, device names, -alternate data streams, names that end in a dot or a space, `\\.\` paths, and `\\?\` -paths other than plain drive and UNC paths such as those `check` returns. -`Roots::required` refuses to build roots without both kinds. A path is checked -before it is opened, so another program that replaces a folder with a link between -the two steps can still reach outside the roots. +given and in the path its links lead to, device names, alternate data streams, +names that end in a dot or a space, `\\.\` and `\??\` paths, and `\\?\` paths +other than plain drive and UNC paths such as those `check` returns. It also +refuses a path on a network share unless a root of the requested kind is on the +same server and share. These Windows checks read only the text of the path and +run before any file system call, so a path whose text names another share does +not open a connection to that computer. A link or junction inside a root that +leads to another share is followed when the path is resolved, which can connect +to that share before the path is refused. `Roots::required` refuses to build +roots without both kinds. A path is checked before it is opened, so another +program that replaces a folder with a link between the two steps can still reach +outside the roots. See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle). diff --git a/crates/mcp/src/roots.rs b/crates/mcp/src/roots.rs index 7e2ef1642d..f47525ebb7 100644 --- a/crates/mcp/src/roots.rs +++ b/crates/mcp/src/roots.rs @@ -17,15 +17,23 @@ //! - On Windows these are refused, in the path as given and again in the path its links lead to: //! device names (`CON`, `NUL`, `COM1`, `LPT¹` and the like, also with an extension), a `:` //! after the drive, a file or folder name that ends in a dot or a space, a path that starts -//! with `\\.\`, and one that starts with `\\?\` unless it is a drive or UNC path with no `/` -//! and no empty, `.` or `..` name, such as a path [`Roots::check`] returned. The names follow -//! . +//! with `\\.\` or `\??\`, and one that starts with `\\?\` unless it is a drive or UNC path with +//! no `/` and no empty, `.` or `..` name, such as a path [`Roots::check`] returned. The names +//! follow . +//! - On Windows a path on a network share (`\\server\share\...` or `\\?\UNC\server\share\...`, +//! also after it is made absolute against the working directory) is refused unless a root of +//! the requested kind is on the same server and share. This check and the name rules on the +//! path as given read only the text of the path, and run before any file system call, so a +//! path whose text names another share does not open a connection to that computer. A link or +//! junction inside a root that leads to another share is followed when the path is resolved, +//! which can connect to that share before the resolved path is refused. Roots are checked +//! against the name rules before they are opened too. //! //! A path is checked and then opened. Another program that swaps a folder for a link between the //! two steps can still reach outside the roots: the roots confine the client's tool arguments, not //! other programs on the computer. -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use std::fmt; use std::path::{Component, Path, PathBuf, Prefix}; @@ -86,7 +94,9 @@ impl fmt::Display for AccessError { AccessError::Device { path } => write!(f, "{} names a device, not a file", path.display()), AccessError::Stream { path } => write!(f, "{} has a `:` in a file or folder name", path.display()), AccessError::TrailingDotOrSpace { path } => write!(f, "{} has a file or folder name that ends in a dot or a space", path.display()), - AccessError::Verbatim { path } => write!(f, r"{} starts with `\\?\` or `\\.\`; give the path without that prefix", path.display()), + AccessError::Verbatim { path } => { + write!(f, r"{} starts with `\\?\`, `\\.\` or `\??\`; give the path without that prefix", path.display()) + } AccessError::ParentOfMissing { path } => write!(f, "{} goes up with `..` below a folder that does not exist", path.display()), AccessError::BrokenLink { path } => write!(f, "{} is a link to something that does not exist", path.display()), AccessError::Unresolved { path, reason } => write!(f, "{} could not be resolved: {reason}", path.display()), @@ -146,6 +156,9 @@ impl Roots { if roots.is_empty() { return Err(AccessError::NotGranted { access, path: path.to_path_buf() }); } + if cfg!(windows) { + check_share(path, access, roots)?; + } let resolved = resolve(path)?; if roots.iter().any(|r| inside(&resolved, r)) { return Ok(resolved); @@ -171,6 +184,9 @@ fn open_all(paths: &[PathBuf], access: Access) -> Result, AccessErr if p.as_os_str().is_empty() { return Err(bad("an empty path names no folder".into())); } + if cfg!(windows) { + check_windows_names(&without_verbatim_prefix(p).map_err(|e| bad(e.to_string()))?).map_err(|e| bad(e.to_string()))?; + } let resolved = std::fs::canonicalize(p).map_err(|e| bad(e.to_string()))?; if !resolved.is_dir() { return Err(bad("it is not a folder".into())); @@ -299,6 +315,38 @@ fn without_verbatim_prefix(path: &Path) -> Result { Ok(plain) } +/// The Windows checks that read only the text of `path`, run before any file system call: the name +/// rules, and a refusal of a path on a network share that holds none of `roots`. A relative path +/// is checked in the absolute form `std::path::absolute` gives it, which on Windows does not touch +/// the file system, so a relative path under a working directory on a share is checked too. +fn check_share(path: &Path, access: Access, roots: &[PathBuf]) -> Result<(), AccessError> { + if path.as_os_str().is_empty() { + return Err(AccessError::Empty); + } + let plain = without_verbatim_prefix(path)?; + check_windows_names(&plain)?; + let absolute = std::path::absolute(&plain).map_err(|e| AccessError::Unresolved { path: path.to_path_buf(), reason: e.to_string() })?; + let Some((server, share)) = network_share(&absolute) else { + return Ok(()); + }; + let same = |r: &PathBuf| network_share(r).is_some_and(|(s, sh)| s.eq_ignore_ascii_case(server) && sh.eq_ignore_ascii_case(share)); + if roots.iter().any(same) { + return Ok(()); + } + Err(AccessError::Outside { access, path: path.to_path_buf(), roots: list(roots) }) +} + +/// The server and share of a `\\server\share` or `\\?\UNC\server\share` path. +fn network_share(path: &Path) -> Option<(&OsStr, &OsStr)> { + match path.components().next() { + Some(Component::Prefix(p)) => match p.kind() { + Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => Some((server, share)), + _ => None, + }, + _ => None, + } +} + /// The Windows name rules applied to a path with its links followed, so a link or junction to a /// folder whose name the rules refuse is refused too. fn check_resolved_names(found: &Path) -> Result<(), AccessError> { @@ -307,6 +355,11 @@ fn check_resolved_names(found: &Path) -> Result<(), AccessError> { /// The Windows name rules from the module documentation. fn check_windows_names(path: &Path) -> Result<(), AccessError> { + // `\??\` passes the rest of the path to Windows as an NT path, without its own name parsing. + let mut first = path.components(); + if first.next() == Some(Component::RootDir) && first.next() == Some(Component::Normal("??".as_ref())) { + return Err(AccessError::Verbatim { path: path.to_path_buf() }); + } for c in path.components() { match c { // These prefixes turn off Windows' own name parsing for the rest of the path. @@ -528,6 +581,48 @@ mod tests { assert!(matches!(refused(r"\\?\Volume{00000000-0000-0000-0000-000000000000}\x.txt"), AccessError::Verbatim { .. })); } + /// These paths are refused from their text alone; a test that reached the file system would + /// try to connect to the server. + #[cfg(windows)] + #[test] + fn network_and_device_paths_are_refused_from_their_text() { + let local = [PathBuf::from(r"\\?\C:\work")]; + let on_share = [PathBuf::from(r"\\?\UNC\server\share\work")]; + let check = |p: &str, roots: &[PathBuf]| check_share(Path::new(p), Access::Read, roots); + for p in [r"\\server\share\x.json", r"\\?\UNC\server\share\x.json", "//server/share/x.json", r"\\server\share"] { + assert!(matches!(check(p, &local), Err(AccessError::Outside { access: Access::Read, .. })), "{p}"); + } + for p in [r"\\server\share\work\x.json", r"\\?\UNC\server\share\work\x.json", r"\\SERVER\Share\elsewhere\x.json"] { + assert_eq!(check(p, &on_share), Ok(()), "a path on the root's share: {p}"); + } + for p in [r"\\other\share\work\x.json", r"\\server\other\work\x.json", r"\\?\UNC\other\share\work"] { + assert!(matches!(check(p, &on_share), Err(AccessError::Outside { .. })), "{p}"); + } + assert_eq!(check(r"C:\work\x.json", &local), Ok(()), "a drive path goes on to be resolved"); + for p in [ + r"\\.\pipe\x", + r"\\.\C:\work\x.json", + r"\\.\UNC\server\share\x.json", + r"\??\UNC\server\share\x.json", + "/??/UNC/server/share/x.json", + r"\??\C:\work\x.json", + r"\\?\GLOBALROOT\Device\Mup\server\share\x.json", + r"\\?\pipe\x", + ] { + for roots in [&local[..], &on_share[..]] { + assert!(matches!(check(p, roots), Err(AccessError::Verbatim { .. })), "{p}"); + } + } + let (base, roots) = folders("network"); + let e = roots.check(Path::new(r"\\craft-roots-test.invalid\share\x.json"), Access::Read).unwrap_err(); + assert!(matches!(e, AccessError::Outside { .. }), "{e}"); + let e = roots.check(Path::new(r"\??\UNC\craft-roots-test.invalid\share\x.json"), Access::Read).unwrap_err(); + assert!(matches!(e, AccessError::Verbatim { .. }), "{e}"); + let e = Roots::new(&[PathBuf::from(r"\??\UNC\craft-roots-test.invalid\share")], &[]).unwrap_err(); + assert!(matches!(&e, AccessError::BadRoot { reason, .. } if reason.contains(r"`\??\`")), "a root is checked before it is opened: {e}"); + let _ = std::fs::remove_dir_all(base); + } + #[cfg(windows)] #[test] fn a_root_whose_resolved_name_the_windows_rules_refuse_is_bad() { From 491773ae4a67da88c548c7e54d5df1d2410bb1b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 18:04:54 -0800 Subject: [PATCH 4/6] craft-mcp: Roots applies the Windows name rules to the absolute path too std::path::absolute turns //?/ and //./ into \?\ and \.\, so a path such as //?/GLOBALROOT/Device/Mup/server/share/x passed the name rules as written and reached the file system. Roots::check and Roots::new now apply the rules again to the absolute form before any file system call. --- crates/mcp/src/roots.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/mcp/src/roots.rs b/crates/mcp/src/roots.rs index f47525ebb7..d28fb73781 100644 --- a/crates/mcp/src/roots.rs +++ b/crates/mcp/src/roots.rs @@ -185,7 +185,10 @@ fn open_all(paths: &[PathBuf], access: Access) -> Result, AccessErr return Err(bad("an empty path names no folder".into())); } if cfg!(windows) { - check_windows_names(&without_verbatim_prefix(p).map_err(|e| bad(e.to_string()))?).map_err(|e| bad(e.to_string()))?; + let plain = without_verbatim_prefix(p).map_err(|e| bad(e.to_string()))?; + check_windows_names(&plain).map_err(|e| bad(e.to_string()))?; + let absolute = std::path::absolute(&plain).map_err(|e| bad(e.to_string()))?; + check_windows_names(&absolute).map_err(|e| bad(e.to_string()))?; } let resolved = std::fs::canonicalize(p).map_err(|e| bad(e.to_string()))?; if !resolved.is_dir() { @@ -326,6 +329,8 @@ fn check_share(path: &Path, access: Access, roots: &[PathBuf]) -> Result<(), Acc let plain = without_verbatim_prefix(path)?; check_windows_names(&plain)?; let absolute = std::path::absolute(&plain).map_err(|e| AccessError::Unresolved { path: path.to_path_buf(), reason: e.to_string() })?; + // `absolute` turns `//?/` and `//./` into `\\?\` and `\\.\`, so the rules run on its result too. + check_windows_names(&absolute)?; let Some((server, share)) = network_share(&absolute) else { return Ok(()); }; @@ -608,6 +613,9 @@ mod tests { r"\??\C:\work\x.json", r"\\?\GLOBALROOT\Device\Mup\server\share\x.json", r"\\?\pipe\x", + "//?/GLOBALROOT/Device/Mup/server/share/x.json", + "//./pipe/x", + r"//?\GLOBALROOT\Device\Mup\server\share\x.json", ] { for roots in [&local[..], &on_share[..]] { assert!(matches!(check(p, roots), Err(AccessError::Verbatim { .. })), "{p}"); @@ -620,6 +628,8 @@ mod tests { assert!(matches!(e, AccessError::Verbatim { .. }), "{e}"); let e = Roots::new(&[PathBuf::from(r"\??\UNC\craft-roots-test.invalid\share")], &[]).unwrap_err(); assert!(matches!(&e, AccessError::BadRoot { reason, .. } if reason.contains(r"`\??\`")), "a root is checked before it is opened: {e}"); + let e = Roots::new(&[PathBuf::from("//?/GLOBALROOT/Device/Mup/craft-roots-test.invalid/share")], &[]).unwrap_err(); + assert!(matches!(&e, AccessError::BadRoot { reason, .. } if reason.contains(r"`\\?\`")), "{e}"); let _ = std::fs::remove_dir_all(base); } From e4f829f6eefce5b9528d2dfabbdea207ead8e2f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:18:07 -0800 Subject: [PATCH 5/6] craft-mcp: Roots refuses paths outside the roots from their text, with one error Roots::check now makes the path absolute, removes its `.` and `..` names from the text, and compares it with each root as given and as resolved before any file system call. Every path outside the roots gets the same Outside error, whether or not something exists there. On Windows and macOS names that differ only in case match in this step. When a path inside a root cannot be resolved and a link in it leads out of the roots, including a chain of links to nothing, the error is Outside too, so the error does not tell what exists outside the roots. --- crates/mcp/README.md | 5 +- crates/mcp/src/roots.rs | 230 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 215 insertions(+), 20 deletions(-) diff --git a/crates/mcp/README.md b/crates/mcp/README.md index 3b82881125..d852df23ab 100644 --- a/crates/mcp/README.md +++ b/crates/mcp/README.md @@ -15,7 +15,10 @@ This crate does not enforce every MCP lifecycle or capability rule; applications must validate any additional requirements they depend on. `roots::Roots` confines the file paths in tool arguments to read and write roots. -`Roots::check` resolves a path, following links, and returns it only when it lies +`Roots::check` first compares the text of the path, made absolute with its `.` and +`..` names removed, with the roots as given and as resolved, before any file system +call, so every path outside the roots gets the same `Outside` error whatever exists +there. It then resolves the path, following links, and returns it only when it lies inside a root of the requested kind. On Windows it also refuses, in the path as given and in the path its links lead to, device names, alternate data streams, names that end in a dot or a space, `\\.\` and `\??\` paths, and `\\?\` paths diff --git a/crates/mcp/src/roots.rs b/crates/mcp/src/roots.rs index d28fb73781..4916b38e77 100644 --- a/crates/mcp/src/roots.rs +++ b/crates/mcp/src/roots.rs @@ -7,13 +7,21 @@ //! //! [`Roots::check`] checks a path like this: //! -//! - It is made absolute against the working directory, then its links are followed. For a path -//! that does not exist yet, the links of its nearest existing folder are followed and the rest -//! must be plain names: `..` below a folder that does not exist is refused, and so is a link -//! that leads nowhere. -//! - The result must be a root or lie inside one, compared folder name by folder name, so `/work2` -//! is not inside `/work`. Following the links gives existing names as the file system stores -//! them, so a path typed in another case still matches on a file system that ignores case. +//! - It is made absolute against the working directory, and its `.` and `..` names are removed +//! from the text. The result must be a root or lie inside one, compared folder name by folder +//! name with the root as it was given or as its links resolve. On Windows and macOS, names that +//! differ only in case match in this step; on other systems they must match exactly, also on a +//! file system that ignores case. The step reads only the text of the path, so every +//! path outside the roots is refused with the same [`AccessError::Outside`], whatever exists +//! there, and a path that reaches a root only through a link outside the roots is refused too. +//! - Then its links are followed. For a path that does not exist yet, the links of its nearest +//! existing folder are followed and the rest must be plain names: `..` below a folder that does +//! not exist is refused, and so is a link that leads nowhere. When the path cannot be resolved +//! and a link in it leads out of the roots, the error is [`AccessError::Outside`] as well. +//! - The result must again be a root or lie inside one, compared folder name by folder name, so +//! `/work2` is not inside `/work`. Following the links gives existing names as the file system +//! stores them, so a path typed in another case still matches on a file system that ignores +//! case. //! - On Windows these are refused, in the path as given and again in the path its links lead to: //! device names (`CON`, `NUL`, `COM1`, `LPT¹` and the like, also with an extension), a `:` //! after the drive, a file or folder name that ends in a dot or a space, a path that starts @@ -106,19 +114,34 @@ impl fmt::Display for AccessError { impl std::error::Error for AccessError {} -/// The read and write roots, each made absolute with its links followed. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +/// The read and write roots, each made absolute with its links followed. Two `Roots` are equal +/// when they hold the same resolved roots. +#[derive(Clone, Debug, Default)] pub struct Roots { read: Vec, write: Vec, + /// Each read root's text as given and as resolved, from [`lexical`]. + read_text: Vec, + /// Each write root's text as given and as resolved, from [`lexical`]. + write_text: Vec, } +impl PartialEq for Roots { + fn eq(&self, other: &Roots) -> bool { + self.read == other.read && self.write == other.write + } +} + +impl Eq for Roots {} + impl Roots { /// Roots from the folders given, which must exist. A folder given twice counts once. Either /// list may be empty; that kind of access is then not granted. On Windows a folder whose path, /// with its links followed, breaks the name rules in the module documentation is refused. pub fn new(read: &[PathBuf], write: &[PathBuf]) -> Result { - Ok(Roots { read: open_all(read, Access::Read)?, write: open_all(write, Access::Write)? }) + let (read, read_text) = open_all(read, Access::Read)?; + let (write, write_text) = open_all(write, Access::Write)?; + Ok(Roots { read, write, read_text, write_text }) } /// [`Roots::new`], refusing roots that leave out either kind. @@ -149,21 +172,35 @@ impl Roots { /// `path` resolved, when it may be used for `access`; otherwise why not. pub fn check(&self, path: &Path, access: Access) -> Result { - let roots = match access { - Access::Read => &self.read, - Access::Write => &self.write, + let (roots, texts) = match access { + Access::Read => (&self.read, &self.read_text), + Access::Write => (&self.write, &self.write_text), }; if roots.is_empty() { return Err(AccessError::NotGranted { access, path: path.to_path_buf() }); } + if path.as_os_str().is_empty() { + return Err(AccessError::Empty); + } if cfg!(windows) { check_share(path, access, roots)?; } - let resolved = resolve(path)?; + let outside = || AccessError::Outside { access, path: path.to_path_buf(), roots: list(roots) }; + // Only the text is read up to here, so a path outside the roots gets the same error + // whether or not something exists there. + let text = lexical(path)?; + if !texts.iter().any(|t| lexically_inside(&text, t)) { + return Err(outside()); + } + let resolved = match resolve(path) { + Ok(resolved) => resolved, + Err(_) if leaves_the_roots(path, roots, texts) => return Err(outside()), + Err(e) => return Err(e), + }; if roots.iter().any(|r| inside(&resolved, r)) { return Ok(resolved); } - Err(AccessError::Outside { access, path: path.to_path_buf(), roots: list(roots) }) + Err(outside()) } /// One line naming the roots, for server instructions and logs. @@ -177,8 +214,10 @@ fn list(roots: &[PathBuf]) -> String { roots.iter().map(|r| display_path(r).display().to_string()).collect::>().join(", ") } -fn open_all(paths: &[PathBuf], access: Access) -> Result, AccessError> { +/// The resolved roots, each once, and the text forms of every root as given and as resolved. +fn open_all(paths: &[PathBuf], access: Access) -> Result<(Vec, Vec), AccessError> { let mut out: Vec = Vec::with_capacity(paths.len()); + let mut texts: Vec = Vec::with_capacity(paths.len() * 2); for p in paths { let bad = |reason: String| AccessError::BadRoot { access, path: p.clone(), reason }; if p.as_os_str().is_empty() { @@ -197,13 +236,115 @@ fn open_all(paths: &[PathBuf], access: Access) -> Result, AccessErr if cfg!(windows) { check_resolved_names(&resolved).map_err(|e| bad(e.to_string()))?; } + for text in [lexical(p), lexical(&resolved)] { + let text = text.map_err(|e| bad(e.to_string()))?; + if !texts.contains(&text) { + texts.push(text); + } + } if !out.iter().any(|r| same_path(r, &resolved)) { out.push(resolved); } } + Ok((out, texts)) +} + +/// `path` made absolute against the working directory, with its `.` and `..` names removed from +/// the text and, on Windows, a `\\?\` drive or UNC prefix removed as [`without_verbatim_prefix`] +/// does. The file system is not asked about the path. +fn lexical(path: &Path) -> Result { + let plain; + let path = if cfg!(windows) { + plain = without_verbatim_prefix(path)?; + plain.as_path() + } else { + path + }; + let absolute = std::path::absolute(path).map_err(|e| AccessError::Unresolved { path: path.to_path_buf(), reason: e.to_string() })?; + let mut out = PathBuf::new(); + for c in absolute.components() { + match c { + Component::CurDir => {} + Component::ParentDir => { + if matches!(out.components().next_back(), Some(Component::Normal(_))) { + out.pop(); + } + } + c => out.push(c), + } + } Ok(out) } +/// The most links [`leaves_the_roots`] follows from one path, the `SYMLOOP_MAX` of Linux. +const MAX_LINKS: usize = 40; + +/// Whether a link inside a root leads `path` out of the roots, for a path that could not be +/// resolved, so the error does not tell what exists outside the roots. The leading parts of the +/// path are resolved one at a time, and the walk stops at the first part that resolves neither +/// inside a root nor to a folder that holds one. Leading parts whose text holds a root's text, as +/// given or as resolved, are skipped until the first `..`. A part that is a link to nothing is +/// followed to its target, which is walked the same way, up to [`MAX_LINKS`] links. Any other part +/// that cannot be resolved leaves the roots unless the part before it is a root or lies inside one. +fn leaves_the_roots(path: &Path, roots: &[PathBuf], texts: &[PathBuf]) -> bool { + leaves_after_links(path, roots, texts, 0) +} + +fn leaves_after_links(path: &Path, roots: &[PathBuf], texts: &[PathBuf], links: usize) -> bool { + if links > MAX_LINKS { + return false; + } + let plain = if cfg!(windows) { without_verbatim_prefix(path).ok() } else { Some(path.to_path_buf()) }; + let Some(absolute) = plain.and_then(|p| std::path::absolute(p).ok()) else { + return false; + }; + let mut at = PathBuf::new(); + let mut leading = true; + // Whether the part before `at` is a root or lies inside one. A part that does not exist below a + // folder that only holds a root lies outside the roots. + let mut parent_inside = false; + for c in absolute.components() { + at.push(c); + // On Windows `C:` alone names the drive's current folder; it is resolved with the `\` after it. + if matches!(c, Component::Prefix(_)) { + continue; + } + let text = lexical(&at); + leading = leading && c != Component::ParentDir && text.as_ref().is_ok_and(|a| texts.iter().any(|t| lexically_inside(t, a))); + if leading { + parent_inside = text.is_ok_and(|a| texts.iter().any(|t| lexically_inside(&a, t))); + continue; + } + let Ok(found) = std::fs::canonicalize(&at) else { + let Ok(target) = std::fs::read_link(&at) else { + return !parent_inside; + }; + let target = match at.parent() { + Some(parent) if target.is_relative() => parent.join(target), + _ => target, + }; + return leaves_after_links(&target, roots, texts, links + 1); + }; + parent_inside = roots.iter().any(|r| inside(&found, r)); + if !parent_inside && !roots.iter().any(|r| inside(r, &found)) { + return true; + } + } + false +} + +/// Whether the text of `path` is `root` or lies inside it, folder name by folder name. Both come +/// from [`lexical`]. On Windows and macOS, names that differ only in case match; the path with its +/// links followed is compared exactly afterwards by [`inside`]. +fn lexically_inside(path: &Path, root: &Path) -> bool { + let fold = cfg!(any(windows, target_os = "macos")); + let same = |p: Component<'_>, r: Component<'_>| { + p == r || (fold && p.as_os_str().to_string_lossy().to_lowercase() == r.as_os_str().to_string_lossy().to_lowercase()) + }; + let mut parts = path.components(); + root.components().all(|r| parts.next().is_some_and(|p| same(p, r))) +} + /// `path` without the `\\?\` prefix of Windows' canonical paths, for messages and logs. On Windows /// a name that has no text form is shown with U+FFFD in its place. Other paths are returned /// unchanged. @@ -460,11 +601,37 @@ mod tests { fn parent_steps_are_resolved_or_refused() { let (base, roots) = folders("dotdot"); let up = base.join("in").join("..").join("outside").join("secret.json"); - assert!(matches!(roots.check(&up, Access::Read), Err(AccessError::Outside { .. })), "an existing path is resolved first"); + assert!(matches!(roots.check(&up, Access::Read), Err(AccessError::Outside { .. })), "`..` that leaves the root"); let back_in = base.join("in").join("sub").join("..").join("show.json"); assert!(roots.check(&back_in, Access::Read).is_ok(), "`..` that stays inside is allowed"); - let below_missing = base.join("in").join("nothing").join("..").join("..").join("outside").join("secret.json"); + let below_missing = base.join("in").join("nothing").join("..").join("show.json"); assert!(matches!(roots.check(&below_missing, Access::Read), Err(AccessError::ParentOfMissing { .. }))); + let out_below_missing = base.join("in").join("nothing").join("..").join("..").join("outside").join("secret.json"); + assert!(matches!(roots.check(&out_below_missing, Access::Read), Err(AccessError::Outside { .. })), "the text leaves the root"); + let _ = std::fs::remove_dir_all(base); + } + + /// The error for a path outside the roots does not depend on what exists there: a missing file, + /// an existing one, a name below a file and `..` below a missing folder all give `Outside`. + #[test] + fn paths_outside_the_roots_get_one_error_whatever_exists_there() { + let (base, roots) = folders("oracle"); + #[cfg(unix)] + std::os::unix::fs::symlink(base.join("outside/none"), base.join("outside/dangling")).unwrap(); + let probes = [ + base.join("outside").join("secret.json"), + base.join("outside").join("missing.json"), + base.join("outside").join("secret.json").join("x.json"), + base.join("outside").join("nothing").join("..").join("secret.json"), + base.join("nowhere").join("at").join("all.json"), + base.join("in").join("..").join("outside").join("nothing").join("..").join("secret.json"), + // A link to nothing on Unix; a missing name elsewhere. + base.join("outside").join("dangling"), + ]; + for p in &probes { + let e = roots.check(p, Access::Read).unwrap_err(); + assert_eq!(e, AccessError::Outside { access: Access::Read, path: p.clone(), roots: list(roots.read()) }, "{}", p.display()); + } let _ = std::fs::remove_dir_all(base); } @@ -507,8 +674,33 @@ mod tests { let (base, roots) = folders("links"); std::os::unix::fs::symlink(base.join("outside"), base.join("in/escape")).unwrap(); std::os::unix::fs::symlink(base.join("outside/none"), base.join("in/dangling")).unwrap(); + std::os::unix::fs::symlink(base.join("in/none"), base.join("in/dangling-in")).unwrap(); assert!(matches!(roots.check(&base.join("in/escape/secret.json"), Access::Read), Err(AccessError::Outside { .. }))); - assert!(matches!(roots.check(&base.join("in/dangling"), Access::Read), Err(AccessError::BrokenLink { .. }))); + assert!(matches!(roots.check(&base.join("in/dangling-in"), Access::Read), Err(AccessError::BrokenLink { .. }))); + // Through a link out of the root, every path gets the same error, whatever exists there. + let outside = |p: &Path| AccessError::Outside { access: Access::Read, path: p.to_path_buf(), roots: list(roots.read()) }; + std::os::unix::fs::symlink(base.join("in/dangling"), base.join("in/hop")).unwrap(); + std::os::unix::fs::symlink(base.join("gone/file"), base.join("in/far")).unwrap(); + for probe in [ + base.join("in/dangling"), + base.join("in/hop"), + base.join("in/far"), + base.join("in/escape/nothing/../secret.json"), + base.join("in/escape/secret.json/../secret.json"), + base.join("in/escape/secret.json/x.json"), + base.join("in/escape/missing/x.json"), + ] { + assert_eq!(roots.check(&probe, Access::Read), Err(outside(&probe)), "{}", probe.display()); + } + // A root given as a link, in a folder that does not hold the folder it leads to, keeps the + // errors of the paths inside it. + std::os::unix::fs::symlink(base.join("in"), base.join("outside/in-link")).unwrap(); + let linked = Roots::new(&[base.join("outside/in-link")], &[]).unwrap(); + let dangling = base.join("outside/in-link/dangling-in"); + assert!(matches!(linked.check(&dangling, Access::Read), Err(AccessError::BrokenLink { .. }))); + let below_missing = base.join("outside/in-link/nothing/../show.json"); + assert!(matches!(linked.check(&below_missing, Access::Read), Err(AccessError::ParentOfMissing { .. }))); + assert!(linked.check(&base.join("outside/in-link/show.json"), Access::Read).is_ok()); let _ = std::fs::remove_dir_all(base); } From 9baea03ef078030b10e6c796a59a39fdcd1eeaa1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:48:39 -0800 Subject: [PATCH 6/6] craft-mcp: Roots resolves a root link before trusting it for an unresolved path When a path below a root could not be resolved, the walk that decides whether it leaves the roots took a part whose text matched a root as inside a root without resolving it. A root given as a link that was changed to lead out of the roots then gave `ParentOfMissing` for `/missing/../x` and `Outside` when that folder existed outside, so the error told whether a folder outside the roots exists. The part that matches a root is now resolved and compared with the roots, and only the folders above a root are skipped from their text. --- crates/mcp/src/roots.rs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/mcp/src/roots.rs b/crates/mcp/src/roots.rs index 4916b38e77..288622f9ac 100644 --- a/crates/mcp/src/roots.rs +++ b/crates/mcp/src/roots.rs @@ -283,7 +283,7 @@ const MAX_LINKS: usize = 40; /// resolved, so the error does not tell what exists outside the roots. The leading parts of the /// path are resolved one at a time, and the walk stops at the first part that resolves neither /// inside a root nor to a folder that holds one. Leading parts whose text holds a root's text, as -/// given or as resolved, are skipped until the first `..`. A part that is a link to nothing is +/// given or as resolved, without being that text, are skipped until the first `..`. A part that is a link to nothing is /// followed to its target, which is walked the same way, up to [`MAX_LINKS`] links. Any other part /// that cannot be resolved leaves the roots unless the part before it is a root or lies inside one. fn leaves_the_roots(path: &Path, roots: &[PathBuf], texts: &[PathBuf]) -> bool { @@ -311,8 +311,10 @@ fn leaves_after_links(path: &Path, roots: &[PathBuf], texts: &[PathBuf], links: } let text = lexical(&at); leading = leading && c != Component::ParentDir && text.as_ref().is_ok_and(|a| texts.iter().any(|t| lexically_inside(t, a))); - if leading { - parent_inside = text.is_ok_and(|a| texts.iter().any(|t| lexically_inside(&a, t))); + // A part whose text is a root's text, or lies inside one, is resolved below like any other, + // so a root given as a link that now leads out of the roots is not trusted from its text. + if leading && !text.is_ok_and(|a| texts.iter().any(|t| lexically_inside(&a, t))) { + parent_inside = false; continue; } let Ok(found) = std::fs::canonicalize(&at) else { @@ -704,6 +706,24 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A root given as a link that is changed to lead out of the roots after the roots are set up + /// gives `Outside` below it, whether or not the folder before a `..` exists there. + #[cfg(unix)] + #[test] + fn a_root_link_changed_to_lead_out_of_the_roots_is_outside() { + let (base, _) = folders("retarget"); + std::os::unix::fs::symlink(base.join("in"), base.join("alias")).unwrap(); + let roots = Roots::new(&[base.join("alias")], &[]).unwrap(); + std::fs::remove_file(base.join("alias")).unwrap(); + std::os::unix::fs::symlink(base.join("outside"), base.join("alias")).unwrap(); + std::fs::create_dir(base.join("outside/probe")).unwrap(); + for probe in [base.join("alias/probe/../secret.json"), base.join("alias/missing/../secret.json")] { + let e = roots.check(&probe, Access::Read); + assert_eq!(e, Err(AccessError::Outside { access: Access::Read, path: probe.clone(), roots: list(roots.read()) }), "{}", probe.display()); + } + let _ = std::fs::remove_dir_all(base); + } + #[test] fn device_names_are_recognized() { for name in ["CON", "nul", "COM1", "lpt9.txt", "AUX ", "COM¹", "lpt³.log", "NUL.tar.gz"] {