use std::sync::LazyLock;
use super::{Frozen, Matcher, REGIONS, Role, absolute_other_home, current_os, secret_node};
use crate::engine::facet::LocalLocus;
#[path = "workspace_roots.rs"]
mod workspace_roots;
pub(super) fn role_is_protective(role: &Role) -> bool {
role.reads_secret
|| role.frozen != Frozen::Nothing
|| role.write_locus > LocalLocus::Worktree
|| role.read_locus > LocalLocus::WorktreeTrusted
}
pub(crate) fn keeps_absolute(abs: &str, root: &str) -> bool {
if crate::pathctx::folder::is_unknown(root) {
return true;
}
let root_cmp = comparable(root);
let home = crate::pathctx::home_dir();
if holds_a_home(&root_cmp, home.as_deref()) || protection_or_ancestor_covers(root) {
return true;
}
let path = comparable(&literal_dir(abs));
REGIONS
.nodes
.iter()
.filter(|n| n.applies_here() && role_is_protective(&n.role))
.filter_map(|n| {
let (place, sub) = fixed_place(&n.matcher)?;
Some((place, sub || n.role.frozen == Frozen::Rebind))
})
.any(|(place, subtree)| {
let place = match (place.strip_prefix('~'), home.as_deref()) {
(Some(rest), Some(h)) => comparable(&format!("{h}{rest}")),
(Some(_), None) => return true,
(None, _) => comparable(&place),
};
(under(&place, &root_cmp) || (subtree && under(&root_cmp, &place)))
&& ((subtree && under(&path, &place)) || under(&place, &path))
})
}
fn region_node_covers(path: &str) -> bool {
let path = super::super::locus::canonicalize(path);
let fold_shields = current_os() == "macos";
REGIONS
.nodes
.iter()
.filter(|n| n.applies_here() && role_is_protective(&n.role))
.any(|n| n.matcher.specificity(&path, n.fold && fold_shields).is_some())
}
fn protection_or_ancestor_covers(path: &str) -> bool {
let Some(norm) = crate::pathctx::join_cwd(None, path).filter(|p| p.starts_with('/')) else {
return region_node_covers(path);
};
let mut cur = norm.as_str();
loop {
if region_node_covers(cur) {
return true;
}
let Some((parent, _)) = cur.rsplit_once('/') else {
return false;
};
if parent.is_empty() {
return region_node_covers("/");
}
cur = parent;
}
}
fn has_disallowed_dot_component(path: &str, home: Option<&str>) -> bool {
let Some(norm) = crate::pathctx::join_cwd(None, path).filter(|p| p.starts_with('/')) else {
return true;
};
if let Some(disqualified) = workspace_roots::dot_disqualifies(&norm, home) {
return disqualified;
}
if let Some(h) = home.map(|h| h.trim_end_matches('/')).filter(|h| !h.is_empty())
&& let Some(rel) = norm.strip_prefix(h).and_then(|r| r.strip_prefix('/'))
{
if let Some(wt_rel) = rel.strip_prefix(".worktrees/") {
return wt_rel.is_empty() || wt_rel.split('/').any(|c| c.starts_with('.'));
}
return rel.split('/').any(|c| c.starts_with('.'));
}
norm.rsplit('/').next().unwrap_or("").starts_with('.')
}
pub(crate) fn is_workspace_root(dir: &str) -> bool {
if !dir.starts_with('/')
|| dir == crate::targets::UNKNOWN_WORKDIR
|| dir == crate::pathctx::UNRESOLVED_CWD
|| dir.contains('$')
|| dir.contains("__SAFE_CHAINS_")
{
return false;
}
let Some(lex) = crate::pathctx::join_cwd(None, dir).filter(|p| p.starts_with('/')) else {
return false;
};
let phys = crate::pathctx::physical_directory(&lex);
if phys == crate::pathctx::UNRESOLVED_CWD {
return false;
}
let home = crate::process_home::var().ok().filter(|h| h.starts_with('/') && h.len() > 1);
let phys_home = home.as_deref().map(crate::pathctx::physical_directory);
let clean = |p: &str, h: Option<&str>| {
!holds_a_home(&comparable(p), h)
&& !protection_or_ancestor_covers(p)
&& !has_disallowed_dot_component(p, h)
&& in_known_workspace(p, h)
};
clean(&lex, home.as_deref()) && clean(&phys, phys_home.as_deref().or(home.as_deref()))
}
fn in_known_workspace(path: &str, home: Option<&str>) -> bool {
if let Some(h) = home.map(|h| h.trim_end_matches('/')).filter(|h| !h.is_empty())
&& let Some(rel) = path.strip_prefix(h).and_then(|r| r.strip_prefix('/'))
&& (rel == "projects" || rel.starts_with("projects/") || (rel.starts_with(".worktrees/") && !rel[".worktrees/".len()..].is_empty()))
{
return true;
}
if workspace_roots::listed(path, home) {
return true;
}
(granted_in_user_config(path) && granted_for_writing(path))
|| path
.strip_prefix("/private")
.filter(|rest| rest.starts_with("/var/") || rest.starts_with("/tmp/") || rest.starts_with("/etc/"))
.is_some_and(|rest| granted_in_user_config(rest) && granted_for_writing(rest))
}
fn granted_in_user_config(path: &str) -> bool {
let canon = super::super::locus::canonicalize(path);
let matches = |grants: &mut dyn Iterator<Item = &super::Grant>| {
for g in grants {
if g.source == super::GrantSource::UserConfig
&& g.write
&& g.matcher.specificity(&canon, false).is_some()
&& !super::has_hidden_component(g.matcher.remainder(&canon))
{
return true;
}
}
false
};
#[cfg(test)]
{
super::TEST_GRANTS.with(|g| super::hypothetical::with_extra(|extra| matches(&mut g.borrow().iter().chain(extra))))
}
#[cfg(not(test))]
{
super::hypothetical::with_extra(|extra| matches(&mut super::USER_GRANTS.iter().chain(extra)))
}
}
fn under(inner: &str, outer: &str) -> bool {
outer == "/" || inner == outer || inner.strip_prefix(outer).is_some_and(|r| r.starts_with('/'))
}
pub(super) fn holds_a_home(root: &str, home: Option<&str>) -> bool {
["/Users", "/home", "/private"].into_iter().chain(home).map(comparable).any(|h| under(&h, root))
}
pub(crate) fn granted_for_writing(path: &str) -> bool {
super::best_grant(&super::super::locus::canonicalize(path), None).is_some_and(|(_, write)| write)
}
pub(crate) fn lies_in_root(placed: &crate::pathctx::Placed, root: &str) -> bool {
let root = comparable(root);
let home = crate::pathctx::home_dir();
root != "/" && !holds_a_home(&root, home.as_deref()) && under(&comparable(placed.judged()), &root)
}
fn literal_dir(path: &str) -> String {
path.split('/').take_while(|c| !c.contains(['*', '?', '['])).collect::<Vec<_>>().join("/")
}
pub(super) fn comparable(path: &str) -> String {
let path = if current_os() == "macos" { super::unicode_spelling::nfc(path) } else { path.to_string() };
let mut parts: Vec<&str> = Vec::new();
for seg in path.split('/') {
match seg {
"" | "." => {}
".." => {
parts.pop();
}
s => parts.push(s),
}
}
let mut out = format!("/{}", parts.join("/"));
if current_os() == "macos" {
out = out.to_ascii_lowercase();
}
out = strip_data_volume(out);
for firm in ["/etc", "/var", "/tmp"] {
let private = format!("/private{firm}");
if out == private || out.starts_with(&format!("{private}/")) {
out = out["/private".len()..].to_string();
}
}
out
}
fn strip_data_volume(path: String) -> String {
let prefix = if current_os() == "macos" { "/system/volumes/data" } else { "/System/Volumes/Data" };
let mut rest = path.as_str();
while rest == prefix || rest.strip_prefix(prefix).is_some_and(|tail| tail.starts_with('/')) {
rest = &rest[prefix.len()..];
if rest.is_empty() {
return "/".to_string();
}
}
if rest.len() == path.len() { path } else { rest.to_string() }
}
fn fixed_place(matcher: &Matcher) -> Option<(String, bool)> {
match matcher {
Matcher::Exact(s) => Some((s.clone(), false)),
Matcher::Prefix(s) => Some((s.clone(), true)),
Matcher::StringPrefix(s) => Some((s.rsplit_once('/').map_or_else(String::new, |(dir, _)| dir.to_string()), true)),
Matcher::Glob(parts) => Some((parts.iter().take_while(|p| !p.contains('*')).cloned().collect::<Vec<_>>().join("/"), true)),
Matcher::Segment(_) => None,
}
}
pub(crate) fn protection_covers(path: &str) -> bool {
let path = super::super::locus::canonicalize(path);
let fold_shields = current_os() == "macos";
absolute_other_home(&path)
|| REGIONS
.nodes
.iter()
.filter(|n| n.applies_here() && role_is_protective(&n.role))
.any(|n| n.matcher.specificity(&path, n.fold && fold_shields).is_some())
}
#[cfg(test)]
pub(crate) fn anchored_protected_paths_here() -> Vec<String> {
super::declared_region_paths()
.into_iter()
.filter(|p| p.starts_with('/') || p.starts_with('~'))
.filter(|p| {
REGIONS
.nodes
.iter()
.any(|n| n.applies_here() && role_is_protective(&n.role) && n.matcher.specificity(p, false).is_some())
})
.collect()
}
pub(crate) fn names_a_region(path: &str) -> bool {
let path = &super::super::locus::canonicalize(path);
let fold = current_os() == "macos";
secret_node(path).is_some()
|| REGIONS
.nodes
.iter()
.any(|n| n.applies_here() && n.matcher.specificity(path, n.fold && fold).is_some())
}
pub(crate) struct HomeNode {
pub segments: Vec<String>,
pub exact: bool,
pub secret: bool,
}
pub(crate) fn home_nodes() -> &'static [HomeNode] {
static NODES: LazyLock<Vec<HomeNode>> = LazyLock::new(|| {
REGIONS
.nodes
.iter()
.filter_map(|n| match &n.matcher {
Matcher::Exact(p) => p.strip_prefix("~/").map(|p| (p, true, n.role.reads_secret)),
Matcher::Prefix(p) => p.strip_prefix("~/").map(|p| (p, false, n.role.reads_secret)),
_ => None,
})
.map(|(p, exact, secret)| HomeNode {
segments: p.split('/').filter(|s| !s.is_empty()).map(str::to_string).collect(),
exact,
secret,
})
.filter(|n| !n.segments.is_empty())
.collect()
});
&NODES
}
pub(crate) fn names_a_secret_text(path: &str) -> bool {
secret_node(&super::super::locus::canonicalize(path)).is_some()
}
#[cfg(test)]
mod names_tests {
use super::*;
#[test]
fn segment_nodes_name_a_relative_path_and_home_nodes_a_home_one() {
for named in
[".git/hooks/pre-commit", "a/.ssh/id_rsa", ".envrc", "~/.ssh/config", "~/.config", "~/Library/LaunchAgents/x.plist", "~/bin/ls"]
{
assert!(names_a_region(named), "{named}");
}
for unnamed in ["src/main.rs", "notes.md", "~/notes.md", "~/projects/app/src/x.rs", "bin/ls"] {
assert!(!names_a_region(unnamed), "{unnamed}");
}
}
#[test]
fn home_nodes_carry_their_segments_and_whether_they_shield_a_secret() {
let find = |p: &[&str]| home_nodes().iter().find(|n| n.segments.iter().map(String::as_str).eq(p.iter().copied()));
let creds = find(&[".cargo", "credentials"]).expect("~/.cargo/credentials");
assert!(creds.exact && creds.secret);
let agents = find(&["Library", "LaunchAgents"]).expect("~/Library/LaunchAgents/");
assert!(!agents.exact && !agents.secret);
assert!(home_nodes().iter().all(|n| !n.segments.is_empty() && n.segments.iter().all(|s| !s.is_empty())));
}
}
#[cfg(test)]
mod tests {
use super::super::with_os;
use super::*;
fn role(read: LocalLocus, write: LocalLocus, reads_secret: bool, frozen: Frozen) -> Role {
Role { read_locus: read, write_locus: write, rebind_locus: write, reads_secret, frozen }
}
#[test]
fn each_stricter_face_alone_makes_a_role_protective() {
let w = LocalLocus::Worktree;
assert!(!role_is_protective(&role(w, w, false, Frozen::Nothing)), "the worktree itself");
assert!(!role_is_protective(&role(LocalLocus::WorktreeTrusted, w, false, Frozen::Nothing)), "a trusted read at the bound");
assert!(role_is_protective(&role(w, w, true, Frozen::Nothing)), "a secret alone");
assert!(role_is_protective(&role(w, w, false, Frozen::Rebind)), "a freeze alone");
assert!(role_is_protective(&role(w, LocalLocus::WorktreeTrusted, false, Frozen::Nothing)), "a write past the worktree alone");
assert!(role_is_protective(&role(LocalLocus::Machine, w, false, Frozen::Nothing)), "a read past the trusted rung alone");
}
#[test]
fn a_root_holding_only_admitted_places_still_resolves_relative() {
assert!(!keeps_absolute("/tmp/x", "/tmp"), "the scratch node admits, it does not protect");
}
#[test]
fn a_glob_node_is_anchored_at_its_literal_directory() {
assert!(keeps_absolute("/proc/1/environ", "/proc"));
assert!(keeps_absolute("/proc", "/proc"), "the root itself is above the protected place");
}
#[test]
fn protection_covers_only_protections_and_folds_case_only_on_macos() {
assert!(!protection_covers("/tmp/x"), "an admit node is not a protection");
assert!(!protection_covers("/srv/app/src"));
assert!(protection_covers("/srv/app/.ssh/id_rsa"));
assert!(with_os("macos", || protection_covers("/srv/app/.SSH/id_rsa")), "one file on a case-insensitive volume");
assert!(!with_os("linux", || protection_covers("/srv/app/.SSH/id_rsa")), "a different directory on Linux");
}
}