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.
This commit is contained in:
dotCooCoo
2026-11-20 20:18:07 -08:00
parent 491773ae4a
commit e4f829f6ee
2 changed files with 215 additions and 20 deletions
+4 -1
View File
@@ -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
+211 -19
View File
@@ -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<PathBuf>,
write: Vec<PathBuf>,
/// Each read root's text as given and as resolved, from [`lexical`].
read_text: Vec<PathBuf>,
/// Each write root's text as given and as resolved, from [`lexical`].
write_text: Vec<PathBuf>,
}
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<Roots, AccessError> {
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<PathBuf, AccessError> {
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::<Vec<_>>().join(", ")
}
fn open_all(paths: &[PathBuf], access: Access) -> Result<Vec<PathBuf>, 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<PathBuf>, Vec<PathBuf>), AccessError> {
let mut out: Vec<PathBuf> = Vec::with_capacity(paths.len());
let mut texts: Vec<PathBuf> = 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<Vec<PathBuf>, 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<PathBuf, AccessError> {
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);
}