use rmcp::model::ResourceContents;
use std::path::Path;
const MAX_FILE_BYTES: u64 = 2 * 1024 * 1024;
#[derive(Debug)]
pub(super) enum FileResourceError {
NotAFilePath,
NotFound(String),
TooLarge(String, u64),
NotUtf8(String),
Io(String, std::io::Error),
OutsideJail(String),
Unbound(String),
Refused(String),
ProtectedContext(String),
}
impl std::fmt::Display for FileResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotAFilePath => write!(f, "Not a file path"),
Self::ProtectedContext(reason) => write!(f, "Protected context: {reason}"),
Self::NotFound(p) => write!(f, "File not found: {p}"),
Self::TooLarge(p, sz) => write!(
f,
"File too large for resource read ({sz} bytes, limit {MAX_FILE_BYTES}): {p}",
),
Self::NotUtf8(p) => write!(
f,
"File is not valid UTF-8 (binary?): {p}. Use ctx_read for binary-safe reads."
),
Self::Io(p, e) => write!(f, "I/O error reading {p}: {e}"),
Self::OutsideJail(p) => write!(
f,
"Path outside project root: {p}. \
Add the parent directory to extra_roots in config.toml if needed."
),
Self::Unbound(p) => write!(
f,
"No project root is bound for this session, so resources/read cannot \
serve {p}. Open the project (start the client in a directory with a \
project marker such as .git), bind one with LEAN_CTX_PROJECT_ROOT, or add \
the parent directory to extra_roots in config.toml."
),
Self::Refused(reason) => write!(f, "Path refused: {reason}"),
}
}
}
pub(super) fn read_file_resource(
uri: &str,
project_root: Option<&str>,
shell_cwd: Option<&str>,
extra_roots: &[String],
) -> Result<Vec<ResourceContents>, FileResourceError> {
let project_root = project_root.filter(|root| !root.is_empty());
let path_str = resolve_path(uri)?;
let path = Path::new(&path_str);
lean_ctx::core::protected_store::enforce_protected_store_path(path)
.map_err(FileResourceError::ProtectedContext)?;
lean_ctx::core::workspace_authority::confine(&path_str, project_root.unwrap_or(""), false)
.map_err(FileResourceError::ProtectedContext)?;
let contained = validate_jail(path, project_root, extra_roots)?;
lean_ctx::core::path_resolve::resolve_tool_path_refusing(
project_root,
shell_cwd,
&path_str,
extra_roots,
)
.map_err(|refusal| FileResourceError::Refused(refusal.message))?;
if !contained.is_file() {
return Err(FileResourceError::NotFound(path_str));
}
let meta =
std::fs::metadata(&contained).map_err(|e| FileResourceError::Io(path_str.clone(), e))?;
if meta.len() > MAX_FILE_BYTES {
return Err(FileResourceError::TooLarge(path_str, meta.len()));
}
let content = std::fs::read_to_string(&contained).map_err(|e| {
if e.kind() == std::io::ErrorKind::InvalidData {
FileResourceError::NotUtf8(path_str.clone())
} else {
FileResourceError::Io(path_str.clone(), e)
}
})?;
Ok(vec![super::resources::text_resource(&content, uri)])
}
fn resolve_path(uri: &str) -> Result<String, FileResourceError> {
if uri.starts_with("file://") {
super::roots::uri_to_path(uri).ok_or(FileResourceError::NotAFilePath)
} else if is_absolute_path(uri) {
Ok(uri.to_string())
} else {
Err(FileResourceError::NotAFilePath)
}
}
fn is_absolute_path(s: &str) -> bool {
s.starts_with('/')
|| (cfg!(windows)
&& s.len() > 2
&& s.as_bytes()[0].is_ascii_alphabetic()
&& s.as_bytes()[1] == b':')
}
fn canonical_or_parent(path: &Path) -> std::path::PathBuf {
if let Ok(canon) = path.canonicalize() {
return canon;
}
match (path.parent(), path.file_name()) {
(Some(parent), Some(name)) => parent
.canonicalize()
.map_or_else(|_| path.to_path_buf(), |parent| parent.join(name)),
_ => path.to_path_buf(),
}
}
fn validate_jail(
path: &Path,
project_root: Option<&str>,
extra_roots: &[String],
) -> Result<std::path::PathBuf, FileResourceError> {
let canon = canonical_or_parent(path);
let unresolved_dots = canon
.components()
.any(|c| matches!(c, std::path::Component::ParentDir));
let roots = project_root
.into_iter()
.chain(extra_roots.iter().map(String::as_str))
.filter(|root| !root.is_empty());
for root in roots {
if !unresolved_dots
&& let Ok(root_canon) = Path::new(root).canonicalize()
&& canon.starts_with(&root_canon)
{
return Ok(canon);
}
}
let shown = path.to_string_lossy().to_string();
Err(if project_root.is_none() {
FileResourceError::Unbound(shown)
} else {
FileResourceError::OutsideJail(shown)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_os = "macos")]
#[test]
fn resource_read_cannot_reopen_runtime_context_with_explicit_roots() {
let isolated = lean_ctx::core::data_dir::isolated_data_dir();
let path = isolated.path().join("knowledge/fixture.json");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "provider-value").unwrap();
let uri = path_to_file_uri(&path);
let root = isolated.path().to_str().unwrap();
assert!(read_file_resource(&uri, Some(root), None, &[]).is_ok());
let _pin = lean_ctx::core::protected_store::pin_synthetic_session(isolated.path()).unwrap();
assert!(matches!(
read_file_resource(&uri, Some(root), None, &[root.to_owned()]),
Err(FileResourceError::ProtectedContext(_))
));
assert!(matches!(
read_file_resource(&uri, None, None, &[]),
Err(FileResourceError::ProtectedContext(_))
));
}
fn path_to_file_uri(p: &std::path::Path) -> String {
let s = p.to_string_lossy().replace('\\', "/");
if s.starts_with('/') {
format!("file://{s}")
} else {
format!("file:///{s}")
}
}
#[cfg(unix)]
#[test]
fn resolve_file_uri() {
let path = resolve_path("file:///tmp/test.txt").unwrap();
assert_eq!(path, "/tmp/test.txt");
}
#[cfg(unix)]
#[test]
fn resolve_raw_absolute_path() {
let path = resolve_path("/home/user/file.rs").unwrap();
assert_eq!(path, "/home/user/file.rs");
}
#[test]
fn resolve_relative_path_returns_not_a_file() {
assert!(matches!(
resolve_path("relative/file.rs"),
Err(FileResourceError::NotAFilePath)
));
}
#[test]
fn resolve_lean_ctx_uri_returns_not_a_file() {
assert!(matches!(
resolve_path("lean-ctx://context/summary"),
Err(FileResourceError::NotAFilePath)
));
}
fn root_of(dir: &tempfile::TempDir) -> String {
dir.path()
.canonicalize()
.unwrap()
.to_string_lossy()
.to_string()
}
#[test]
fn unresolvable_dot_dot_never_counts_as_inside() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let dir = tempfile::tempdir().unwrap();
let root = root_of(&dir);
let escape = format!(
"{}/missing/../../../../../../etc/hostname",
dir.path().to_string_lossy()
);
let result = read_file_resource(&escape, Some(&root), None, &[]);
assert!(
matches!(result, Err(FileResourceError::OutsideJail(_))),
"{result:?}"
);
}
#[test]
fn read_nonexistent_file_inside_root() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let dir = tempfile::tempdir().unwrap();
let root = root_of(&dir);
let uri = path_to_file_uri(&dir.path().join("does_not_exist.txt"));
let result = read_file_resource(&uri, Some(&root), None, &[]);
assert!(
matches!(result, Err(FileResourceError::NotFound(_))),
"{result:?}"
);
}
#[cfg(unix)]
#[test]
fn unbound_session_refuses_system_files() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
for system in ["/etc/hostname", "/etc/hosts", "/etc/passwd"] {
if !Path::new(system).is_file() {
continue;
}
for uri in [format!("file://{system}"), system.to_string()] {
let result = read_file_resource(&uri, None, None, &[]);
assert!(
matches!(result, Err(FileResourceError::Unbound(_))),
"{uri}: {result:?}"
);
let shell_cwd = std::env::current_dir().unwrap();
let result =
read_file_resource(&uri, None, Some(&shell_cwd.to_string_lossy()), &[]);
assert!(
matches!(result, Err(FileResourceError::Unbound(_))),
"{uri}: {result:?}"
);
let result = read_file_resource(&uri, Some(""), None, &[]);
assert!(
matches!(result, Err(FileResourceError::Unbound(_))),
"{uri}: {result:?}"
);
}
}
}
#[test]
fn unbound_session_refuses_a_project_outside_every_root() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let project = tempfile::tempdir().unwrap();
std::fs::create_dir_all(project.path().join(".git")).unwrap();
let file = project.path().join("README.md");
std::fs::write(&file, "project").unwrap();
let cwd = root_of(&project);
for uri in [path_to_file_uri(&file), file.to_string_lossy().to_string()] {
for shell_cwd in [None, Some(cwd.as_str())] {
let result = read_file_resource(&uri, None, shell_cwd, &[]);
let err = result.unwrap_err();
assert!(
matches!(err, FileResourceError::Unbound(_)),
"{uri}: {err:?}"
);
let text = err.to_string();
assert!(
text.contains("No project root") && text.contains("extra_roots"),
"{text}"
);
}
}
}
#[test]
fn unbound_session_serves_its_extra_roots() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let extra = tempfile::tempdir().unwrap();
let file = extra.path().join("notes.txt");
std::fs::write(&file, "allowed").unwrap();
let roots = vec![root_of(&extra)];
let result = read_file_resource(&path_to_file_uri(&file), None, None, &roots);
assert!(result.is_ok(), "{result:?}");
}
#[test]
fn read_file_outside_jail() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let jail = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let file = outside.path().join("secret.txt");
std::fs::write(&file, "secret").unwrap();
let root = root_of(&jail);
for uri in [path_to_file_uri(&file), file.to_string_lossy().to_string()] {
let result = read_file_resource(&uri, Some(&root), Some(&root), &[]);
assert!(
matches!(result, Err(FileResourceError::OutsideJail(_))),
"{result:?}"
);
}
}
#[test]
fn read_file_inside_jail() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let jail = tempfile::tempdir().unwrap();
let file = jail.path().join("test.txt");
std::fs::write(&file, "allowed").unwrap();
let root = root_of(&jail);
for uri in [path_to_file_uri(&file), file.to_string_lossy().to_string()] {
let result = read_file_resource(&uri, Some(&root), Some(&root), &[]);
assert_eq!(result.unwrap().len(), 1);
}
}
#[test]
fn bound_root_also_serves_extra_roots() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let jail = tempfile::tempdir().unwrap();
let extra = tempfile::tempdir().unwrap();
let file = extra.path().join("shared.txt");
std::fs::write(&file, "shared").unwrap();
let root = root_of(&jail);
let uri = path_to_file_uri(&file);
assert!(matches!(
read_file_resource(&uri, Some(&root), None, &[]),
Err(FileResourceError::OutsideJail(_))
));
let roots = vec![root_of(&extra)];
let result = read_file_resource(&uri, Some(&root), None, &roots);
assert!(result.is_ok(), "{result:?}");
}
#[cfg(unix)]
#[test]
fn symlink_inside_root_to_outside_is_refused() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let jail = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let target = outside.path().join("secret.txt");
std::fs::write(&target, "secret").unwrap();
let link = jail.path().join("link.txt");
std::os::unix::fs::symlink(&target, &link).unwrap();
let root = root_of(&jail);
let result = read_file_resource(&path_to_file_uri(&link), Some(&root), None, &[]);
assert!(
matches!(result, Err(FileResourceError::OutsideJail(_))),
"{result:?}"
);
let dir_link = jail.path().join("out");
std::os::unix::fs::symlink(outside.path(), &dir_link).unwrap();
let via_dir = dir_link.join("secret.txt");
let result = read_file_resource(&path_to_file_uri(&via_dir), Some(&root), None, &[]);
assert!(
matches!(result, Err(FileResourceError::OutsideJail(_))),
"{result:?}"
);
let result = read_file_resource(&path_to_file_uri(&link), None, None, &[]);
assert!(
matches!(result, Err(FileResourceError::Unbound(_))),
"{result:?}"
);
}
#[test]
fn resource_read_follows_the_tool_jail_inside_the_root() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let jail = tempfile::tempdir().unwrap();
let root = root_of(&jail);
std::fs::create_dir_all(jail.path().join(".ssh")).unwrap();
for name in [".env", ".ssh/id_rsa", "plain.txt"] {
let file = jail.path().join(name);
std::fs::write(&file, "value").unwrap();
let path = file.to_string_lossy().to_string();
let tool = lean_ctx::core::path_resolve::resolve_tool_path_refusing(
Some(&root),
Some(&root),
&path,
&[],
);
let resource = read_file_resource(&path, Some(&root), Some(&root), &[]);
assert_eq!(tool.is_ok(), resource.is_ok(), "{name}: {resource:?}");
if tool.is_err() {
assert!(
matches!(resource, Err(FileResourceError::Refused(_))),
"{name}"
);
}
}
}
#[cfg(unix)]
#[test]
fn dot_dot_out_of_the_root_is_refused() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let parent = tempfile::tempdir().unwrap();
let jail = parent.path().join("project");
std::fs::create_dir_all(&jail).unwrap();
std::fs::write(parent.path().join("secret.txt"), "secret").unwrap();
let root = jail.canonicalize().unwrap().to_string_lossy().to_string();
let escaped = format!("{root}/../secret.txt");
let result = read_file_resource(&escaped, Some(&root), None, &[]);
assert!(
matches!(result, Err(FileResourceError::OutsideJail(_))),
"{result:?}"
);
}
#[test]
fn non_file_uri_is_not_a_file_path() {
assert!(matches!(
read_file_resource("https://example.com", None, None, &[]),
Err(FileResourceError::NotAFilePath)
));
}
}