use super::SandboxPolicy;
use base::paths::{
entry, ENGINE_CONFIG_DIRS, ENGINE_CONFIG_FILES, GIT_CONTROL_FILES, GIT_HOOKS_DIR,
GIT_WORKTREES_DIR, GIT_WORKTREE_CONTROL_FILES, PROJECT_ENGINE_CONFIG_DIRS,
PROJECT_STATE_ENGINE_DIRS, REPOSITORY_CONFIG_DIR, STATE_ROOT_SESSION_TMP,
STATE_ROOT_WORKING_DIRS,
};
use std::path::{Path, PathBuf};
pub(super) struct Roots {
pub(super) cwd: PathBuf,
pub(super) worktree_git: Option<base::paths::WorktreeGit>,
pub(super) only_additional: bool,
pub(super) writable: Vec<PathBuf>,
pub(super) read_only: Vec<PathBuf>,
pub(super) state_root: Option<PathBuf>,
pub(super) foreign_state_roots: Vec<PathBuf>,
pub(super) paths: base::paths::SensitivePaths,
}
impl Roots {
pub(super) fn resolve(cwd: &Path, additional: &[PathBuf], policy: &SandboxPolicy) -> Self {
let cwd = base::path::resolve_physically(cwd);
let state_root = policy
.state_root
.as_deref()
.map(base::path::resolve_physically);
let paths = base::paths::SensitivePaths::new(
state_root.as_deref(),
Some(&cwd),
policy.layout.clone(),
)
.with_foreign_state_roots(
&policy
.foreign_state_roots
.iter()
.map(|root| base::path::resolve_physically(root))
.collect::<Vec<_>>(),
);
Self {
foreign_state_roots: paths.foreign_state_roots(),
paths,
cwd,
worktree_git: policy
.worktree_git
.as_ref()
.map(|git| base::paths::WorktreeGit {
dir: base::path::resolve_physically(&git.dir),
admin: base::path::resolve_physically(&git.admin),
branch: git.branch.clone(),
}),
only_additional: policy.only_additional_writable,
writable: additional
.iter()
.map(|p| base::path::resolve_physically(p))
.collect(),
read_only: policy
.read_only_dirs
.iter()
.map(|p| base::path::resolve_physically(p))
.collect(),
state_root,
}
}
pub(super) fn write_roots(&self) -> impl Iterator<Item = &Path> {
(!self.only_additional)
.then_some(self.cwd.as_path())
.into_iter()
.chain(self.writable.iter().map(PathBuf::as_path))
}
pub(super) fn opens(&self, path: &Path) -> bool {
(!self.only_additional && path.starts_with(&self.cwd))
|| self.writable.iter().any(|root| path.starts_with(root))
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(super) fn read_only_in_reach(&self) -> impl Iterator<Item = &Path> {
self.read_only
.iter()
.filter(|dir| self.opens(dir) || self.write_roots().any(|root| root.starts_with(dir)))
.map(PathBuf::as_path)
}
#[cfg_attr(not(any(target_os = "macos", target_os = "linux")), allow(dead_code))]
pub(super) fn movable_above(&self, dir: &Path) -> Vec<PathBuf> {
let roots: Vec<PathBuf> = self
.write_roots()
.map(Path::to_path_buf)
.chain(super::implicit_writable_roots(self.only_additional))
.collect();
dir.ancestors()
.skip(1)
.filter(|p| roots.iter().any(|root| p.starts_with(root) && p != root))
.map(Path::to_path_buf)
.collect()
}
#[cfg_attr(not(any(target_os = "macos", target_os = "linux")), allow(dead_code))]
pub(super) fn configuration_in(&self, real: &Path) -> Configuration {
let state = real.join(entry::STATE);
Configuration {
files: ENGINE_CONFIG_FILES.iter().map(|f| real.join(f)).collect(),
dirs: ENGINE_CONFIG_DIRS
.iter()
.map(|d| real.join(d))
.chain(PROJECT_STATE_ENGINE_DIRS.iter().map(|d| state.join(d)))
.chain([state.join(self.paths.layout().product_id())])
.collect(),
}
}
pub(super) fn unfenced_state_root_config(&self) -> (Vec<PathBuf>, Vec<PathBuf>) {
let Some(root) = self
.state_root
.as_deref()
.filter(|_| self.fenced_state_root().is_none())
else {
return Default::default();
};
let guarded = |names: &[&str]| -> Vec<PathBuf> {
names
.iter()
.map(|name| root.join(name))
.filter(|p| self.opens(p) && !self.cwd.starts_with(p))
.collect()
};
(guarded(ENGINE_CONFIG_FILES), guarded(ENGINE_CONFIG_DIRS))
}
pub(super) fn session_temp_dirs_in<'a>(
&'a self,
root: &Path,
) -> impl Iterator<Item = &'a PathBuf> {
let tmp = root.join(STATE_ROOT_SESSION_TMP);
self.writable
.iter()
.filter(move |p| p.starts_with(&tmp) && **p != tmp)
}
pub(super) fn fenced_state_root(&self) -> Option<&Path> {
self.state_root
.as_deref()
.filter(|root| !self.only_additional && !self.project_in(root))
}
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(super) fn fenced_foreign_state_roots(&self) -> impl Iterator<Item = &Path> {
self.foreign_state_roots
.iter()
.map(PathBuf::as_path)
.filter(|root| !self.cwd.starts_with(root))
}
pub(super) fn project_in(&self, state_root: &Path) -> bool {
self.cwd.starts_with(state_root)
&& !STATE_ROOT_WORKING_DIRS
.iter()
.any(|dir| self.cwd.starts_with(state_root.join(dir)))
}
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(super) fn denied_for_write(name: &str, denied: &[String]) -> bool {
denied.iter().any(|d| {
name == d
|| name
.strip_prefix(d.as_str())
.is_some_and(|r| r.starts_with('.'))
})
}
pub(super) fn write_denial_names(denied: &[String]) -> Vec<String> {
denied
.iter()
.filter(|d| !d.is_empty() && !d.contains('/'))
.cloned()
.collect()
}
const LINK_SEARCH_DEPTH: usize = 4;
const LINK_SEARCH_ENTRIES: usize = 4096;
pub(super) fn link_targets_outside(dir: &Path) -> Vec<PathBuf> {
let real = base::path::resolve_physically(dir);
let mut found = Vec::new();
let mut pending = vec![(dir.to_path_buf(), 0)];
let mut looked_at = 0;
while let Some((at, depth)) = pending.pop() {
let Ok(entries) = std::fs::read_dir(&at) else {
continue;
};
for entry in entries.flatten() {
looked_at += 1;
if looked_at > LINK_SEARCH_ENTRIES {
return found;
}
let Ok(kind) = entry.file_type() else {
continue;
};
if kind.is_symlink() {
let target = base::path::resolve_physically(&entry.path());
if !target.starts_with(&real) && !found.contains(&target) {
found.push(target);
}
} else if kind.is_dir() && depth < LINK_SEARCH_DEPTH {
pending.push((entry.path(), depth + 1));
}
}
}
found
}
pub(super) fn subdirs(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
entries
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.map(|e| e.path())
.collect()
}
const SUBMODULE_SEARCH_DEPTH: usize = 12;
const SUBMODULE_LIMIT: usize = 256;
#[derive(Default)]
pub(super) struct Submodules {
pub(super) dirs: Vec<PathBuf>,
pub(super) git_dirs: Vec<PathBuf>,
}
pub(super) fn submodules_of(git_dir: &Path) -> Submodules {
let mut found = Submodules::default();
let mut pending = vec![(git_dir.join("modules"), 0)];
while let Some((dir, depth)) = pending.pop() {
if depth >= SUBMODULE_SEARCH_DEPTH || found.git_dirs.len() >= SUBMODULE_LIMIT {
continue;
}
if !dir.symlink_metadata().is_ok_and(|m| m.is_dir()) {
continue;
}
found.dirs.push(dir.clone());
for child in subdirs(&dir) {
let is_git_dir = ["HEAD", "config"]
.iter()
.any(|f| child.join(f).symlink_metadata().is_ok());
if is_git_dir {
found.dirs.push(child.clone());
pending.push((child.join("modules"), depth + 1));
found.git_dirs.push(child);
} else {
pending.push((child, depth + 1));
}
}
}
found
}
#[derive(Default)]
pub(super) struct GitConfigured {
pub(super) hooks: Option<PathBuf>,
pub(super) included: Vec<PathBuf>,
}
pub(super) fn git_configured(cwd: &Path, git_dir: &Path) -> GitConfigured {
let mut found = GitConfigured::default();
let home = base::paths::home_dir();
let mut seen = Vec::new();
read_git_config(
&git_dir.join("config"),
cwd,
home.as_deref(),
&mut seen,
&mut found,
);
found
}
fn read_git_config(
config: &Path,
cwd: &Path,
home: Option<&Path>,
seen: &mut Vec<PathBuf>,
found: &mut GitConfigured,
) {
let config = base::path::resolve_physically(config);
if seen.contains(&config) || seen.len() >= 32 {
return;
}
seen.push(config.clone());
let Ok(text) = std::fs::read_to_string(&config) else {
return;
};
let named = |value: &str, relative_to: &Path| match (value.strip_prefix("~/"), home) {
(Some(rest), Some(home)) => home.join(rest),
_ => relative_to.join(value),
};
let mut section = String::new();
for line in text.lines().map(str::trim) {
if let Some(header) = line.strip_prefix('[') {
section = header
.split(|c: char| c == ']' || c.is_whitespace() || c == '"')
.next()
.unwrap_or_default()
.to_ascii_lowercase();
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
let (key, value) = (key.trim().to_ascii_lowercase(), config_value(value));
match (section.as_str(), key.as_str()) {
("core", "hookspath") if !value.is_empty() => {
let hooks = base::path::resolve_physically(&named(&value, cwd));
found.hooks = Some(hooks).filter(|h| !cwd.starts_with(h));
}
("include" | "includeif", "path") if !value.is_empty() => {
let included = base::path::resolve_physically(&named(
&value,
config.parent().unwrap_or(Path::new("/")),
));
found.included.push(included.clone());
read_git_config(&included, cwd, home, seen, found);
}
_ => {}
}
}
}
fn config_value(raw: &str) -> String {
let mut out = String::new();
let mut quoted = false;
for c in raw.trim().chars() {
match c {
'"' => quoted = !quoted,
'#' | ';' if !quoted => break,
_ => out.push(c),
}
}
out.trim().to_string()
}
pub(super) struct Configuration {
pub(super) files: Vec<PathBuf>,
pub(super) dirs: Vec<PathBuf>,
}
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(super) struct ProjectGuard {
pub(super) entries: Vec<PathBuf>,
pub(super) files: Vec<PathBuf>,
pub(super) trees: Vec<PathBuf>,
pub(super) shut: Vec<PathBuf>,
pub(super) working: Vec<PathBuf>,
pub(super) worktree_parents: WorktreeParents,
}
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(super) struct WorktreeParents {
pub(super) admin: Vec<PathBuf>,
pub(super) links: Vec<PathBuf>,
}
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(super) fn project_guard(roots: &Roots) -> ProjectGuard {
let cwd = roots.cwd.as_path();
let git = cwd.join(REPOSITORY_CONFIG_DIR);
let git_dir = roots
.worktree_git
.as_ref()
.map(|g| g.dir.clone())
.unwrap_or_else(|| base::path::resolve_physically(&git));
let mut entries = vec![git.clone()];
if git_dir != git {
entries.push(git_dir.clone());
}
let submodules = submodules_of(&git_dir);
entries.extend(submodules.dirs);
let mut files = Vec::new();
let mut trees = Vec::new();
let mut admin = Vec::new();
for repo in std::iter::once(&git_dir).chain(&submodules.git_dirs) {
files.extend(GIT_CONTROL_FILES.iter().map(|f| repo.join(f)));
trees.push(repo.join(GIT_HOOKS_DIR));
for worktree in subdirs(&repo.join(GIT_WORKTREES_DIR)) {
files.extend(GIT_WORKTREE_CONTROL_FILES.iter().map(|f| worktree.join(f)));
}
admin.push(repo.join(GIT_WORKTREES_DIR));
}
if roots.worktree_git.is_some() {
trees.push(git_dir.join(GIT_OBJECTS_INFO_DIR));
}
let configured = git_configured(cwd, &git_dir);
trees.extend(configured.hooks);
files.extend(configured.included);
let (mut shut, mut working) = (Vec::new(), Vec::new());
for root in roots.paths.config_roots_in(cwd) {
let real = root.resolved.clone();
let configuration = roots.configuration_in(&real);
files.extend(configuration.files);
trees.extend(configuration.dirs);
entries.push(real.join(entry::STATE));
working.extend(root.working_entries());
shut.push(real.clone());
if real != root.path {
entries.push(real);
}
entries.push(root.path);
}
for dir in PROJECT_ENGINE_CONFIG_DIRS {
let mut above = cwd.to_path_buf();
for part in Path::new(dir).components() {
above.push(part);
let real = base::path::resolve_physically(&above);
if real != above {
entries.push(real);
}
entries.push(above.clone());
}
trees.push(base::path::resolve_physically(&above));
}
let links: Vec<PathBuf> = roots
.paths
.worktree_dirs_in(cwd)
.iter()
.map(|dir| base::path::resolve_physically(dir))
.collect();
for worktree in links.iter().flat_map(|dir| subdirs(dir)) {
files.push(worktree.join(REPOSITORY_CONFIG_DIR));
}
ProjectGuard {
entries,
files,
trees,
shut,
working,
worktree_parents: WorktreeParents { admin, links },
}
}
pub(super) const GIT_OBJECTS_INFO_DIR: &str = "objects/info";