use std::collections::VecDeque;
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
pub const DEFAULT_BLOCKED_PREFIXES: &[&str] = &[
"/etc", "/usr", "/boot", "/sys", "/proc", "/dev", "/root", "/var/log", "/var/run", "/run",
];
const MAX_SYMLINK_HOPS: usize = 40;
fn normalize_lexical(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for comp in path.components() {
match comp {
Component::CurDir => {}
Component::ParentDir => {
let _ = out.pop();
}
other => out.push(other.as_os_str()),
}
}
out
}
fn join_components(parts: &[OsString]) -> PathBuf {
let mut path = PathBuf::new();
for part in parts {
path.push(part);
}
path
}
pub(crate) fn glob_static_prefix(pattern: &str) -> &str {
let meta_idx = pattern.find(['*', '?', '[']).unwrap_or(pattern.len());
let prefix = &pattern[..meta_idx];
match prefix.rfind('/') {
Some(i) if i > 0 => &pattern[..i],
Some(_) => "/", None => ".",
}
}
fn canonicalize_prefix(p: &Path) -> PathBuf {
let mut tail: Vec<OsString> = Vec::new();
let mut ancestor = p;
while !ancestor.exists() {
match (ancestor.file_name(), ancestor.parent()) {
(Some(name), Some(parent)) if parent != ancestor => {
tail.push(name.to_os_string());
ancestor = parent;
}
_ => return normalize_lexical(p),
}
}
let mut out = ancestor
.canonicalize()
.unwrap_or_else(|_| normalize_lexical(ancestor));
for comp in tail.iter().rev() {
out.push(comp);
}
out
}
fn expand_tilde(raw: &str, home: Option<&Path>) -> Result<PathBuf, String> {
if raw == "~" {
return home
.map(|p| p.to_path_buf())
.ok_or_else(|| format!("allowed_paths entry '{raw}' needs a home directory"));
}
let Some(rest) = raw.strip_prefix("~/") else {
return Err(format!(
"allowed_paths entry '{raw}' uses an unsupported '~user' form; use '~/…' or an absolute path"
));
};
home.map(|p| p.join(rest))
.ok_or_else(|| format!("allowed_paths entry '{raw}' needs a home directory"))
}
#[derive(Debug)]
pub struct PathGuardBuilder {
root: PathBuf,
allowed_raw: Vec<String>,
extra_blocked: Vec<String>,
blocked_override: Option<Vec<String>>,
home: Option<PathBuf>,
}
impl PathGuardBuilder {
pub fn allowed_paths<I, S>(mut self, paths: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.allowed_raw.extend(paths.into_iter().map(Into::into));
self
}
pub fn extra_blocked_paths<I, S>(mut self, paths: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.extra_blocked.extend(paths.into_iter().map(Into::into));
self
}
pub fn blocked_paths<I, S>(mut self, paths: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.blocked_override = Some(paths.into_iter().map(Into::into).collect());
self
}
pub fn home(mut self, home: Option<&Path>) -> Self {
self.home = home.map(|p| p.to_path_buf());
self
}
fn effective_blocked(&self) -> Vec<PathBuf> {
let raw: Vec<String> = match &self.blocked_override {
Some(list) => list.clone(),
None => DEFAULT_BLOCKED_PREFIXES
.iter()
.map(|s| (*s).to_string())
.chain(self.extra_blocked.iter().cloned())
.collect(),
};
raw.iter()
.map(|s| normalize_lexical(Path::new(s)))
.collect()
}
pub fn build(self) -> Result<PathGuard, String> {
let canonical_root = self.root.canonicalize().map_err(|e| {
format!(
"Failed to canonicalize workspace root '{}': {}",
self.root.display(),
e
)
})?;
if !canonical_root.is_dir() {
return Err(format!(
"Workspace root '{}' is not a directory",
self.root.display()
));
}
let blocked = self.effective_blocked();
let home = self.home.as_deref();
let mut allowed = Vec::new();
for entry in &self.allowed_raw {
let trimmed = entry.trim();
if trimmed.is_empty() {
continue;
}
let expanded = if trimmed.starts_with('~') {
expand_tilde(trimmed, home)
.map_err(|e| format!("invalid allowed_paths entry '{entry}': {e}"))?
} else if Path::new(trimmed).is_absolute() {
PathBuf::from(trimmed)
} else {
canonical_root.join(trimmed)
};
let normalized = normalize_lexical(&expanded);
let resolved_entry = canonicalize_prefix(&expanded);
if blocked.iter().any(|b| {
normalized.starts_with(b)
|| b.starts_with(&normalized)
|| resolved_entry.starts_with(b)
|| b.starts_with(&resolved_entry)
}) {
tracing::warn!(
"allowed_paths entry '{}' overlaps a blocked prefix — ignoring it",
entry
);
continue;
}
allowed.push(resolved_entry);
}
Ok(PathGuard {
root: canonical_root,
allowed,
blocked,
})
}
}
#[derive(Debug, Clone)]
pub struct PathGuard {
root: PathBuf,
allowed: Vec<PathBuf>,
blocked: Vec<PathBuf>,
}
impl PathGuard {
pub fn builder(root: &Path) -> PathGuardBuilder {
PathGuardBuilder {
root: root.to_path_buf(),
allowed_raw: Vec::new(),
extra_blocked: Vec::new(),
blocked_override: None,
home: None,
}
}
pub fn new(root: &Path) -> Result<Self, String> {
Self::builder(root).build()
}
pub fn configured(
root: &Path,
allowed: &[String],
home: Option<&Path>,
extra_blocked: &[String],
) -> Result<Self, String> {
Self::builder(root)
.allowed_paths(allowed.iter().cloned())
.extra_blocked_paths(extra_blocked.iter().cloned())
.home(home)
.build()
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn allowed_roots(&self) -> &[PathBuf] {
&self.allowed
}
pub fn blocked_prefixes(&self) -> &[PathBuf] {
&self.blocked
}
fn covers(&self, p: &Path) -> bool {
if p.starts_with(&self.root) {
return true;
}
if self.blocked.iter().any(|b| p.starts_with(b)) {
return false;
}
self.allowed.iter().any(|a| p.starts_with(a))
}
pub fn resolve_contained(&self, raw: &str) -> Result<PathBuf, String> {
if raw.trim().is_empty() {
return Err(self.violation_message(raw));
}
let candidate = Path::new(raw);
let joined = if candidate.is_absolute() {
candidate.to_path_buf()
} else {
self.root.join(candidate)
};
let lexical = normalize_lexical(&joined);
if !self.covers(&lexical) {
let resolved = self
.resolve_kernel_order(&joined)
.ok_or_else(|| self.violation_message(raw))?;
if !self.covers(&resolved) {
return Err(self.violation_message(raw));
}
return Ok(resolved);
}
let resolved = self
.resolve_kernel_order(&joined)
.ok_or_else(|| self.violation_message(raw))?;
if !self.covers(&resolved) {
return Err(self.violation_message(raw));
}
Ok(resolved)
}
fn resolve_kernel_order(&self, joined: &Path) -> Option<PathBuf> {
debug_assert!(joined.is_absolute());
let mut out: Vec<OsString> = vec![OsString::from("/")];
let mut rest: VecDeque<OsString> = joined
.components()
.filter(|c| !matches!(c, Component::RootDir))
.map(|c| OsString::from(c.as_os_str()))
.collect();
let mut hops = 0;
while let Some(comp) = rest.pop_front() {
match comp.to_str() {
Some(".") => continue,
Some("..") => {
if out.len() > 1 {
out.pop();
}
continue;
}
_ => {}
}
out.push(comp);
let candidate = join_components(&out);
let meta = match std::fs::symlink_metadata(&candidate) {
Ok(meta) => meta,
Err(_) => continue,
};
if !meta.file_type().is_symlink() {
continue;
}
hops += 1;
if hops > MAX_SYMLINK_HOPS {
return None;
}
let target = std::fs::read_link(&candidate).ok()?;
out.pop();
if target.is_absolute() {
out.clear();
out.push(OsString::from("/"));
}
let splice = target
.components()
.filter(|c| !matches!(c, Component::RootDir))
.map(|c| OsString::from(c.as_os_str()))
.collect::<Vec<_>>();
for item in splice.into_iter().rev() {
rest.push_front(item);
}
}
Some(join_components(&out))
}
pub fn contains(&self, raw: &str) -> bool {
self.resolve_contained(raw).is_ok()
}
pub fn open_read_contained(&self, path: &Path) -> Result<std::fs::File, String> {
let file = std::fs::File::open(path)
.map_err(|e| format!("Error opening '{}': {}", path.display(), e))?;
self.verify_open_file(&file, path)?;
Ok(file)
}
pub fn create_contained(&self, path: &Path) -> Result<std::fs::File, String> {
let file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path)
.map_err(|e| format!("Error opening '{}' for writing: {}", path.display(), e))?;
self.verify_open_file(&file, path)?;
Ok(file)
}
pub fn open_dir_contained(&self, path: &Path) -> Result<std::fs::File, String> {
let file = std::fs::File::open(path)
.map_err(|e| format!("Error opening directory '{}': {}", path.display(), e))?;
self.verify_open_file(&file, path)?;
Ok(file)
}
pub fn read_contained(&self, path: &Path) -> Result<String, String> {
use std::io::Read;
let mut file = self.open_read_contained(path)?;
let mut buf = String::new();
file.read_to_string(&mut buf)
.map_err(|e| format!("Error reading '{}': {}", path.display(), e))?;
Ok(buf)
}
pub fn write_contained(&self, path: &Path, content: &str) -> Result<(), String> {
use std::io::Write;
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
self.create_dir_all_contained(parent)?;
}
let mut file = self.create_contained(path)?;
file.write_all(content.as_bytes())
.map_err(|e| format!("Error writing '{}': {}", path.display(), e))?;
Ok(())
}
pub fn create_dir_all_contained(&self, dir: &Path) -> Result<(), String> {
let mut missing: Vec<OsString> = Vec::new();
let mut ancestor = dir;
while !ancestor.exists() {
match (ancestor.file_name(), ancestor.parent()) {
(Some(name), Some(parent)) if parent != ancestor => {
missing.push(name.to_os_string());
ancestor = parent;
}
_ => return Err(self.violation_message(&dir.to_string_lossy())),
}
}
self.verify_open_file(
&std::fs::File::open(ancestor)
.map_err(|e| format!("Error opening directory '{}': {}", ancestor.display(), e))?,
dir,
)?;
let mut cur = ancestor.to_path_buf();
for comp in missing.iter().rev() {
cur.push(comp);
let _ = std::fs::create_dir(&cur);
let f = std::fs::File::open(&cur)
.map_err(|e| format!("Error opening directory '{}': {}", cur.display(), e))?;
self.verify_open_file(&f, dir)?;
}
Ok(())
}
#[cfg(all(unix, not(target_os = "macos")))]
fn verify_open_file(&self, file: &std::fs::File, display: &Path) -> Result<(), String> {
use std::os::unix::io::AsRawFd;
let link = format!("/proc/self/fd/{}", file.as_raw_fd());
let real = std::fs::read_link(&link).map_err(|e| {
format!(
"Error: cannot verify opened file '{}' ({}); refusing it",
display.display(),
e
)
})?;
if !self.covers(&real) {
return Err(self.violation_message(&real.to_string_lossy()));
}
Ok(())
}
#[cfg(target_os = "macos")]
fn verify_open_file(&self, file: &std::fs::File, display: &Path) -> Result<(), String> {
use std::os::unix::ffi::OsStringExt;
use std::os::unix::io::AsRawFd;
let mut buf = vec![0u8; libc::PATH_MAX as usize];
let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) };
if ret != 0 {
return Err(format!(
"Error: cannot verify opened file '{}' (F_GETPATH failed); refusing it",
display.display()
));
}
let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
let real = PathBuf::from(std::ffi::OsString::from_vec(buf[..len].to_vec()));
if !self.covers(&real) {
return Err(self.violation_message(&real.to_string_lossy()));
}
Ok(())
}
#[cfg(not(unix))]
fn verify_open_file(&self, _file: &std::fs::File, _display: &Path) -> Result<(), String> {
Ok(())
}
pub fn check_glob_pattern(&self, pattern: &str) -> Result<(), String> {
let base = glob_static_prefix(pattern);
self.resolve_contained(base).map(|_| ())
}
pub fn violation_message(&self, raw: &str) -> String {
let mut msg = format!(
"Error: Path '{}' is outside the workspace root '{}'. \
File-tool access is confined to the workspace",
raw,
self.root.display()
);
if self.allowed.is_empty() {
msg.push_str(". Add directories to `allowed_paths` in settings.json to widen it.");
} else {
let roots: Vec<String> = self
.allowed
.iter()
.map(|p| format!("'{}'", p.display()))
.collect();
msg.push_str(&format!(" (also allowed: {}).", roots.join(", ")));
}
msg
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
fn guard_in(tmp: &Path) -> PathGuard {
PathGuard::new(tmp).unwrap()
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn open_descriptor_is_verified_after_the_race() {
let tmp = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
std::fs::write(outside.path().join("secret.txt"), "CANARY").unwrap();
let root = tmp.path().join("root");
std::fs::create_dir_all(root.join("sub")).unwrap();
std::fs::write(root.join("sub/secret.txt"), "local").unwrap();
let sb = guard_in(&root);
let resolved = sb.resolve_contained("sub/secret.txt").unwrap();
assert_eq!(sb.read_contained(&resolved).unwrap(), "local");
std::fs::remove_dir_all(root.join("sub")).unwrap();
std::os::unix::fs::symlink(outside.path(), root.join("sub")).unwrap();
let err = sb.open_read_contained(&resolved).unwrap_err();
assert!(err.contains("outside the workspace"), "err: {err}");
assert!(sb.read_contained(&resolved).is_err());
assert!(sb.write_contained(&resolved, "PWN").is_err());
assert_eq!(
std::fs::read_to_string(outside.path().join("secret.txt")).unwrap(),
"CANARY"
);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn create_dir_all_contained_verifies_each_new_directory() {
let tmp = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
std::fs::create_dir_all(&root).unwrap();
let sb = guard_in(&root);
std::os::unix::fs::symlink(outside.path(), root.join("sub")).unwrap();
let target = root.join("sub/new-dir/file.txt");
assert!(sb.write_contained(&target, "PWN").is_err());
assert!(!outside.path().join("new-dir").exists());
}
#[test]
fn normalize_lexical_resolves_dotdot() {
let p = normalize_lexical(Path::new("/a/b/../c/./d"));
assert_eq!(p, PathBuf::from("/a/c/d"));
}
#[test]
fn normalize_lexical_clamps_at_root() {
let p = normalize_lexical(Path::new("/a/../../etc/passwd"));
assert_eq!(p, PathBuf::from("/etc/passwd"));
}
#[test]
fn new_requires_existing_dir() {
assert!(PathGuard::new(Path::new("/definitely/not/a/real/dir")).is_err());
}
#[test]
fn contains_absolute_inside() {
let tmp = tempfile::tempdir().unwrap();
let sb = guard_in(tmp.path());
let inside = sb.root().join("file.txt");
assert!(sb.contains(inside.to_str().unwrap()));
}
#[test]
fn contains_absolute_outside() {
let tmp = tempfile::tempdir().unwrap();
let sb = guard_in(tmp.path());
assert!(!sb.contains("/etc/passwd"));
let other = tempfile::tempdir().unwrap();
assert!(!sb.contains(other.path().join("x.txt").to_str().unwrap()));
}
#[test]
fn contains_relative_paths() {
let tmp = tempfile::tempdir().unwrap();
let sb = guard_in(tmp.path());
assert!(sb.contains("file.txt"));
assert!(sb.contains("./sub/dir/file.txt"));
assert!(sb.contains("sub/../other.txt"));
}
#[test]
fn rejects_dotdot_traversal() {
let tmp = tempfile::tempdir().unwrap();
let sb = guard_in(tmp.path());
assert!(!sb.contains("../escape.txt"));
assert!(!sb.contains("sub/../../escape.txt"));
let traversal = format!("{}/../outside.txt", sb.root().display());
assert!(!sb.contains(&traversal));
}
#[test]
fn allows_nonexistent_paths_inside_root() {
let tmp = tempfile::tempdir().unwrap();
let sb = guard_in(tmp.path());
assert!(sb.contains("does/not/exist/yet.txt"));
let resolved = sb.resolve_contained("new/nested/file.rs").unwrap();
assert!(resolved.starts_with(sb.root()));
assert!(resolved.ends_with("new/nested/file.rs"));
}
#[test]
fn rejects_nonexistent_paths_outside_root() {
let tmp = tempfile::tempdir().unwrap();
let sb = guard_in(tmp.path());
assert!(!sb.contains("/tmp/path-guard-evil-dir-xyz/new.txt"));
}
#[test]
fn rejects_symlink_escape() {
let tmp = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let sb = guard_in(tmp.path());
let link = tmp.path().join("evil_link");
std::os::unix::fs::symlink(outside.path(), &link).unwrap();
assert!(!sb.contains("evil_link/secret.txt"));
assert!(!sb.contains(link.to_str().unwrap()));
}
#[test]
fn violation_message_mentions_path_and_root() {
let tmp = tempfile::tempdir().unwrap();
let sb = guard_in(tmp.path());
let msg = sb.violation_message("/etc/passwd");
assert!(msg.contains("/etc/passwd"));
assert!(msg.contains(&sb.root().display().to_string()));
assert!(msg.starts_with("Error: Path '"));
}
#[test]
fn rejects_empty_path() {
let tmp = tempfile::tempdir().unwrap();
let sb = guard_in(tmp.path());
assert!(!sb.contains(""));
assert!(!sb.contains(" "));
}
#[test]
fn allowed_paths_widen_the_guard() {
let tmp = tempfile::tempdir().unwrap();
let extra = tempfile::tempdir().unwrap();
let sb = PathGuard::configured(
tmp.path(),
&[extra.path().to_string_lossy().to_string()],
None,
&[],
)
.unwrap();
assert!(sb.contains(extra.path().join("file.txt").to_str().unwrap()));
assert!(!sb.contains("/etc/hosts"));
}
#[test]
fn relative_allowed_path_is_joined_with_root() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("shared")).unwrap();
let sb = PathGuard::configured(tmp.path(), &["shared".to_string()], None, &[]).unwrap();
assert!(sb.contains("shared/a.txt"));
assert!(sb.contains(tmp.path().join("shared/b.txt").to_str().unwrap()));
}
#[test]
fn tilde_allowed_path_needs_home() {
let tmp = tempfile::tempdir().unwrap();
let err =
PathGuard::configured(tmp.path(), &["~/.cargo".to_string()], None, &[]).unwrap_err();
assert!(err.contains("home directory"), "{err}");
let home = tempfile::tempdir().unwrap();
let sb = PathGuard::configured(
tmp.path(),
&["~/.cargo".to_string()],
Some(home.path()),
&[],
)
.unwrap();
let cargo = home.path().join(".cargo");
assert!(sb.contains(cargo.join("registry/index").to_str().unwrap()));
}
#[test]
fn blocked_prefix_defeats_overbroad_allowed_root() {
let tmp = tempfile::tempdir().unwrap();
let sb = PathGuard::configured(tmp.path(), &["/".to_string()], None, &[]).unwrap();
assert!(sb.allowed_roots().is_empty());
assert!(!sb.contains("/etc/passwd"));
assert!(!sb.contains("/usr/lib/libc.so"));
let other = tempfile::tempdir().unwrap();
assert!(!sb.contains(other.path().join("x.txt").to_str().unwrap()));
}
#[test]
fn workspace_root_is_exempt_from_blocked_prefixes() {
let tmp = tempfile::tempdir().unwrap();
let sb = PathGuard::configured(tmp.path(), &["/".to_string()], None, &[]).unwrap();
assert!(sb.contains("inside-me/etc/passwd"));
}
#[test]
fn overbroad_allowed_entry_is_reported_not_fatal() {
let tmp = tempfile::tempdir().unwrap();
let sb = PathGuard::configured(tmp.path(), &["/etc".to_string()], None, &[]).unwrap();
assert!(sb.allowed_roots().is_empty());
assert!(!sb.contains("/etc/passwd"));
}
#[test]
fn ancestor_of_a_blocked_prefix_is_not_allowed() {
let tmp = tempfile::tempdir().unwrap();
for entry in ["/", "/var", "/run/.."] {
let sb = PathGuard::configured(tmp.path(), &[entry.to_string()], None, &[]).unwrap();
assert!(
sb.allowed_roots().is_empty(),
"entry {entry:?} must be dropped, got {:?}",
sb.allowed_roots()
);
}
let sb = PathGuard::configured(tmp.path(), &["/".to_string()], None, &[]).unwrap();
assert!(!sb.contains("/etc/passwd"));
assert!(!sb.contains("/var/log/auth.log"));
assert!(!sb.contains("/home/user/.bashrc"));
}
#[test]
fn sibling_of_a_blocked_prefix_is_allowed() {
let tmp = tempfile::tempdir().unwrap();
let sb = PathGuard::configured(tmp.path(), &["/var/lib".to_string()], None, &[]).unwrap();
assert_eq!(sb.allowed_roots().len(), 1);
assert!(!sb.contains("/var/log/auth.log"));
}
#[test]
fn glob_pattern_uses_static_prefix() {
let tmp = tempfile::tempdir().unwrap();
let sb = guard_in(tmp.path());
assert!(sb.check_glob_pattern("**/*.rs").is_ok());
assert!(sb.check_glob_pattern("src/**/*.toml").is_ok());
assert!(sb.check_glob_pattern("/etc/**").is_err());
assert!(sb.check_glob_pattern("../secret/*.txt").is_err());
}
#[test]
fn rejects_symlink_then_dotdot_reaching_outside() {
let tmp = tempfile::tempdir().unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(Path::new("/usr"), &link).unwrap();
let sb = guard_in(tmp.path());
assert!(!sb.contains("link/../etc/passwd"));
assert!(!sb.contains(&format!("{}/link/../etc/passwd", tmp.path().display())));
assert!(!sb.contains("link/../outside_me.txt"));
}
#[test]
fn rejects_symlink_then_dotdot_into_sibling() {
let tmp = tempfile::tempdir().unwrap();
let parent = tmp.path().parent().unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(parent, &link).unwrap();
let sb = guard_in(tmp.path());
assert!(!sb.contains("link/../sibling-secret.txt"));
}
#[test]
fn symlink_dotdot_cannot_reach_a_blocked_prefix() {
let tmp = tempfile::tempdir().unwrap();
std::os::unix::fs::symlink(Path::new("/usr"), tmp.path().join("link")).unwrap();
let sb = PathGuard::configured(tmp.path(), &["/".to_string()], None, &[]).unwrap();
assert!(!sb.contains("link/../etc/passwd"));
assert!(!sb.contains("link/../usr/lib"));
}
#[test]
fn follows_relative_symlink_chains_in_kernel_order() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("a")).unwrap();
std::fs::create_dir_all(tmp.path().join("b")).unwrap();
std::fs::write(tmp.path().join("b/target.txt"), "x").unwrap();
std::os::unix::fs::symlink(Path::new("../b"), tmp.path().join("a/one")).unwrap();
let sb = guard_in(tmp.path());
assert!(sb.contains("a/one/target.txt"));
let resolved = sb.resolve_contained("a/one/../target.txt").unwrap();
assert_eq!(resolved, sb.root().join("target.txt"));
}
#[test]
fn rejects_symlink_loop() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a");
let b = tmp.path().join("b");
std::os::unix::fs::symlink(&b, &a).unwrap();
std::os::unix::fs::symlink(&a, &b).unwrap();
let sb = guard_in(tmp.path());
assert!(!sb.contains("a/x.txt"));
assert!(!sb.contains("b/x.txt"));
}
#[test]
fn root_and_allowed_entries_reached_through_a_symlink_still_match() {
let tmp = tempfile::tempdir().unwrap();
let real = tmp.path().join("real");
std::fs::create_dir_all(real.join("proj")).unwrap();
std::fs::create_dir_all(real.join("extra")).unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&real, &link).unwrap();
let spelled_root = link.join("proj");
let spelled_extra = link.join("extra");
let sb = PathGuard::configured(
&spelled_root,
&[spelled_extra.to_string_lossy().to_string()],
None,
&[],
)
.unwrap();
assert_eq!(sb.root(), real.join("proj").canonicalize().unwrap());
assert!(sb.contains(spelled_root.join("file.txt").to_str().unwrap()));
assert!(sb.contains(spelled_extra.join("f.txt").to_str().unwrap()));
assert!(sb.contains(real.join("proj/file.txt").to_str().unwrap()));
assert!(sb.contains(real.join("extra/f.txt").to_str().unwrap()));
assert!(!sb.contains("/etc/passwd"));
assert!(!sb.contains(link.join("../outside.txt").to_str().unwrap()));
}
#[test]
fn glob_pattern_honours_allowed_root() {
let tmp = tempfile::tempdir().unwrap();
let extra = tempfile::tempdir().unwrap();
let sb = PathGuard::configured(
tmp.path(),
&[extra.path().to_string_lossy().to_string()],
None,
&[],
)
.unwrap();
let pattern = format!("{}/**/*.rs", extra.path().display());
assert!(sb.check_glob_pattern(&pattern).is_ok());
}
}