use std::ffi::OsStr;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[cfg(unix)]
use std::cell::{Cell, RefCell};
#[cfg(unix)]
use std::collections::HashMap;
use crate::agent_lock::{AgentLockError, load_agent_lock};
use crate::guard::{PathGuard, PathGuardError};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DenyPolicy {
globs: Arc<Vec<String>>,
}
impl Default for DenyPolicy {
fn default() -> Self {
Self {
globs: Arc::new(default_secret_denies()),
}
}
}
impl DenyPolicy {
pub fn new(globs: Vec<String>) -> Self {
Self {
globs: Arc::new(globs),
}
}
pub fn from_arc(globs: Arc<Vec<String>>) -> Self {
Self { globs }
}
pub fn globs_arc(&self) -> Arc<Vec<String>> {
Arc::clone(&self.globs)
}
pub fn with_extra(extra: impl IntoIterator<Item = String>) -> Self {
let mut globs = default_secret_denies();
for g in extra {
if !globs.iter().any(|x| x == &g) {
globs.push(g);
}
}
Self {
globs: Arc::new(globs),
}
}
pub fn from_workspace(path: impl AsRef<Path>) -> Result<Self, AgentLockError> {
Ok(Self::with_extra(load_agent_lock(path.as_ref())?))
}
pub fn globs(&self) -> &[String] {
&self.globs
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DestDenyKind {
DenyGlob,
HardlinkSibling,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DestDeny {
pub kind: DestDenyKind,
pub path: PathBuf,
pub display: String,
pub matched: Option<String>,
}
impl DestDeny {
pub fn message(&self) -> String {
match (&self.kind, self.matched.as_deref()) {
(DestDenyKind::DenyGlob, Some(glob)) => format!(
"path denied by sandbox profile (matches deny glob {glob}): {}",
self.display
),
(DestDenyKind::DenyGlob, None) => format!(
"path denied by sandbox profile (matches deny glob): {}",
self.display
),
(DestDenyKind::HardlinkSibling, Some(sib)) => format!(
"path denied by sandbox profile (hardlink of a denied name {sib}): {}",
self.display
),
(DestDenyKind::HardlinkSibling, None) => format!(
"path denied by sandbox profile (hardlink of a denied name): {}",
self.display
),
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum DestDenyError {
#[error("{0}")]
Denied(DestDeny),
#[error("command references path denied by sandbox profile: {token}")]
CommandToken { token: String },
#[error("invalid -EncodedCommand payload (need UTF-16LE base64); child was not started")]
EncodedCommand,
#[error(
"PowerShell stdin script (-Command - or -File -) cannot be dest-denied; child was not started"
)]
StdinScript,
#[error(
"path denied: {path} is a hardlink of a denied name; unlink extra names or do not share the inode"
)]
LateHardlink { path: String },
#[error("TOCTOU race detected: {path} changed between check and open")]
Toctou { path: String },
#[error("TOCTOU check failed: {0}")]
ToctouStat(String),
}
#[derive(Debug, thiserror::Error)]
pub enum CheckDestError {
#[error(transparent)]
DestDeny(#[from] DestDenyError),
#[error(transparent)]
PathGuard(#[from] PathGuardError),
#[error("path contains a NUL byte")]
Nul,
#[error("refuse special file ({kind}): {path}")]
SpecialFile { path: String, kind: &'static str },
#[error("refuse directory read: {path}")]
Directory { path: String },
#[error("open failed: {0}")]
Io(String),
#[error("command argument is not valid UTF-8")]
NonUtf8,
}
impl std::fmt::Display for DestDeny {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message())
}
}
pub fn classify_dest(path: &Path, policy: &DenyPolicy) -> Option<DestDenyKind> {
classify_dest_hit(path, policy).map(|hit| hit.kind)
}
struct DestDenyHit {
kind: DestDenyKind,
matched: Option<String>,
}
fn classify_dest_hit(path: &Path, policy: &DenyPolicy) -> Option<DestDenyHit> {
classify_dest_hit_root(path, policy, None)
}
fn ancestor_deny_glob(path: &Path, policy: &DenyPolicy, root: Option<&Path>) -> Option<String> {
let mut cursor = path.parent();
while let Some(dir) = cursor {
if dir.as_os_str().is_empty() {
break;
}
if dir.is_absolute()
&& let Some(root) = root
&& !ancestor_inside_workspace(dir, root)
{
break;
}
if let Some(glob) = deny_glob_name(first_matching_deny_glob_under(
policy.globs(),
&path_as_glob(dir),
root,
)) {
return Some(glob);
}
let next = dir.parent();
if next == Some(dir) {
break;
}
cursor = next;
}
None
}
fn ancestor_inside_workspace(dir: &Path, root: &Path) -> bool {
let dir_s = path_as_glob(dir);
for spelling in firmlink_spellings(root) {
let root_s = path_as_glob(&spelling).trim_end_matches('/').to_string();
if root_s.is_empty() {
continue;
}
let prefix = format!("{root_s}/");
if dir_s.len() > prefix.len()
&& dir_s.is_char_boundary(prefix.len())
&& dir_s[..prefix.len()].eq_ignore_ascii_case(&prefix)
{
return true;
}
}
false
}
fn classify_dest_hit_root(
path: &Path,
policy: &DenyPolicy,
root: Option<&Path>,
) -> Option<DestDenyHit> {
if let Some(glob) = deny_glob_name(first_matching_deny_glob_under(
policy.globs(),
&path_as_glob(path),
root,
)) {
return Some(DestDenyHit {
kind: DestDenyKind::DenyGlob,
matched: Some(glob),
});
}
let canon = std::fs::canonicalize(path).ok();
if let Some(canon) = &canon
&& let Some(glob) = deny_glob_name(first_matching_deny_glob_under(
policy.globs(),
&path_as_glob(canon),
root,
))
{
return Some(DestDenyHit {
kind: DestDenyKind::DenyGlob,
matched: Some(glob),
});
}
if let Some(glob) = ancestor_deny_glob(path, policy, root) {
return Some(DestDenyHit {
kind: DestDenyKind::DenyGlob,
matched: Some(glob),
});
}
if let Some(canon) = &canon
&& let Some(glob) = ancestor_deny_glob(canon, policy, root)
{
return Some(DestDenyHit {
kind: DestDenyKind::DenyGlob,
matched: Some(glob),
});
}
match hardlink_sibling_hit(path, canon.as_deref(), policy, root) {
HardlinkHit::Denied { sibling } => Some(DestDenyHit {
kind: DestDenyKind::HardlinkSibling,
matched: sibling,
}),
HardlinkHit::Allowed => None,
}
}
pub(crate) fn dest_deny_at(
classified: &Path,
display: String,
policy: &DenyPolicy,
) -> Option<DestDeny> {
dest_deny_at_root(classified, display, policy, None)
}
pub(crate) fn dest_deny_at_root(
classified: &Path,
display: String,
policy: &DenyPolicy,
root: Option<&Path>,
) -> Option<DestDeny> {
classify_dest_hit_root(classified, policy, root).map(|hit| DestDeny {
kind: hit.kind,
path: classified.to_path_buf(),
display,
matched: hit.matched,
})
}
pub(crate) fn dest_deny_glob_only(
classified: &Path,
display: String,
policy: &DenyPolicy,
) -> Option<DestDeny> {
first_matching_deny_glob(policy.globs(), &path_as_glob(classified)).map(|glob| DestDeny {
kind: DestDenyKind::DenyGlob,
path: classified.to_path_buf(),
display,
matched: Some(glob),
})
}
pub fn is_path_denied(path: &Path, policy: &DenyPolicy) -> bool {
classify_dest(path, policy).is_some()
}
pub fn dest_deny_message(path: &Path, display: &str, policy: &DenyPolicy) -> Option<String> {
dest_deny_at(path, display.to_owned(), policy).map(|d| d.message())
}
pub fn check_dest(
path: &str,
policy: &DenyPolicy,
guard: Option<&PathGuard>,
) -> Result<PathBuf, CheckDestError> {
check_dest_rooted(path, policy, guard, None)
}
fn check_dest_rooted(
path: &str,
policy: &DenyPolicy,
guard: Option<&PathGuard>,
workspace: Option<&Path>,
) -> Result<PathBuf, CheckDestError> {
if path.contains('\0') {
return Err(CheckDestError::Nul);
}
let raw = Path::new(path);
let glob_root = workspace.or_else(|| guard.map(|g| g.canon_root()));
if let Some(deny) = dest_deny_at_root(raw, path.to_owned(), policy, glob_root) {
return Err(CheckDestError::DestDeny(DestDenyError::Denied(deny)));
}
#[cfg(unix)]
if is_null_device(raw) {
return Ok(raw.to_path_buf());
}
#[cfg(windows)]
if let Some(kind) = windows_device_kind(path) {
return match kind {
WinDev::Null => Ok(raw.to_path_buf()),
WinDev::Other => Err(CheckDestError::SpecialFile {
path: path.to_owned(),
kind: "device",
}),
};
}
let resolved = match guard {
Some(g) => match g.check(raw) {
Ok(checked) => checked,
Err(err) => {
reject_special_file(raw)?;
return Err(err.into());
}
},
None => {
let joined = if raw.is_absolute() {
raw.to_path_buf()
} else {
match std::env::current_dir() {
Ok(cwd) => cwd.join(raw),
Err(_) => raw.to_path_buf(),
}
};
if joined.exists() {
std::fs::canonicalize(&joined).unwrap_or(joined)
} else {
joined
}
}
};
if let Some(deny) = dest_deny_at_root(&resolved, path.to_owned(), policy, glob_root) {
return Err(CheckDestError::DestDeny(DestDenyError::Denied(deny)));
}
reject_special_file(&resolved)?;
Ok(resolved)
}
pub fn open_verified_read(
path: &str,
policy: &DenyPolicy,
guard: Option<&PathGuard>,
) -> Result<File, CheckDestError> {
let resolved = check_dest(path, policy, guard)?;
refuse_directory(&resolved)?;
let file = File::open(&resolved).map_err(|e| CheckDestError::Io(e.to_string()))?;
if file.metadata().map(|m| m.is_dir()).unwrap_or(false) {
return Err(directory_read_error(&resolved));
}
verify_post_open(&resolved, &file, policy)?;
Ok(file)
}
fn refuse_directory(path: &Path) -> Result<(), CheckDestError> {
let Ok(meta) = std::fs::metadata(path) else {
return Ok(());
};
if meta.is_dir() {
return Err(directory_read_error(path));
}
Ok(())
}
fn directory_read_error(path: &Path) -> CheckDestError {
CheckDestError::Directory {
path: path.display().to_string(),
}
}
#[cfg(unix)]
pub(crate) fn is_null_device(path: &Path) -> bool {
use std::os::unix::fs::FileTypeExt;
use std::os::unix::fs::MetadataExt;
let Ok(meta) = std::fs::metadata(path) else {
return false;
};
if !meta.file_type().is_char_device() {
return false;
}
let Ok(null_meta) = std::fs::metadata("/dev/null") else {
return false;
};
null_meta.file_type().is_char_device() && meta.rdev() == null_meta.rdev()
}
fn reject_special_file(path: &Path) -> Result<(), CheckDestError> {
#[cfg(unix)]
{
use std::os::unix::fs::FileTypeExt;
let Ok(meta) = std::fs::metadata(path) else {
return Ok(());
};
let ft = meta.file_type();
let kind = if ft.is_fifo() {
Some("fifo")
} else if ft.is_socket() {
Some("socket")
} else if ft.is_char_device() || ft.is_block_device() {
Some("device")
} else {
None
};
if let Some(kind) = kind {
if kind == "device" && is_null_device(path) {
return Ok(());
}
return Err(CheckDestError::SpecialFile {
path: path.display().to_string(),
kind,
});
}
}
#[cfg(windows)]
{
if let Some(text) = path.to_str()
&& windows_device_kind(text) == Some(WinDev::Other)
{
return Err(CheckDestError::SpecialFile {
path: path.display().to_string(),
kind: "device",
});
}
}
#[cfg(not(any(unix, windows)))]
{
let _ = path;
}
Ok(())
}
#[cfg(windows)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum WinDev {
Null,
Other,
}
#[cfg(windows)]
fn windows_device_kind(text: &str) -> Option<WinDev> {
if let Some(rest) = device_namespace_body(text) {
let rest = rest.trim_end_matches(['\\', '/']);
if rest.contains('\\') || rest.contains('/') {
return None;
}
return reserved_device_name(rest);
}
let component = text.rsplit(['\\', '/']).next().unwrap_or(text);
reserved_device_name(component).or_else(|| reserved_two_colons(component))
}
#[cfg(windows)]
fn device_namespace_body(text: &str) -> Option<&str> {
let bytes = text.as_bytes();
if bytes.len() < 4 {
return None;
}
let sep = bytes[0];
if (sep != b'\\' && sep != b'/') || bytes[1] != sep || bytes[3] != sep {
return None;
}
let mark = bytes[2].to_ascii_lowercase();
if mark != b'.' && mark != b'?' {
return None;
}
Some(&text[4..])
}
#[cfg(windows)]
fn reserved_device_name(component: &str) -> Option<WinDev> {
let trimmed = component.trim_end_matches([' ', '.']);
let name = match trimmed.strip_suffix(':') {
Some(head) => {
let head = head.trim_end_matches([' ', '.']);
if head.is_empty() || head.contains(':') || head.contains('.') {
trimmed
} else {
head
}
}
None => trimmed,
};
classify_reserved(name)
}
#[cfg(windows)]
fn reserved_two_colons(component: &str) -> Option<WinDev> {
if let Some(head) = component.strip_suffix("::") {
if head.is_empty() || head.ends_with([' ', '.', ':']) {
return None;
}
return classify_reserved(head);
}
let bytes = component.as_bytes();
let mut i = bytes.len();
if i == 0 || bytes[i - 1] != b':' {
return None;
}
i -= 1;
if i == 0 || bytes[i - 1] != b' ' {
return None;
}
while i > 0 && bytes[i - 1] == b' ' {
i -= 1;
}
if i == 0 || bytes[i - 1] != b':' {
return None;
}
i -= 1;
while i > 0 && bytes[i - 1] == b' ' {
i -= 1;
}
classify_reserved(&component[..i])
}
#[cfg(windows)]
fn classify_reserved(name: &str) -> Option<WinDev> {
if name.is_empty() || name.contains('.') || name.contains(':') || name.contains(' ') {
return None;
}
match name.to_ascii_uppercase().as_str() {
"NUL" => Some(WinDev::Null),
"CON" | "PRN" | "AUX" | "CONIN$" | "CONOUT$" => Some(WinDev::Other),
other => {
let rest = other
.strip_prefix("COM")
.or_else(|| other.strip_prefix("LPT"))?;
match rest.as_bytes() {
[digit] if (b'1'..=b'9').contains(digit) => Some(WinDev::Other),
_ => None,
}
}
}
}
pub fn verify_post_open(path: &Path, fd: &File, policy: &DenyPolicy) -> Result<(), DestDenyError> {
#[cfg(unix)]
{
verify_post_open_unix(path, fd, policy)
}
#[cfg(windows)]
{
verify_post_open_windows(path, fd, policy)
}
#[cfg(not(any(unix, windows)))]
{
let _ = (path, fd, policy);
Ok(())
}
}
#[cfg(unix)]
fn verify_post_open_unix(path: &Path, fd: &File, policy: &DenyPolicy) -> Result<(), DestDenyError> {
use std::os::unix::fs::MetadataExt;
let path_meta = std::fs::symlink_metadata(path)
.map_err(|e| DestDenyError::ToctouStat(format!("cannot stat {}: {e}", path.display())))?;
let fd_meta = fd
.metadata()
.map_err(|e| DestDenyError::ToctouStat(format!("cannot fstat fd: {e}")))?;
if path_meta.ino() != fd_meta.ino() || path_meta.dev() != fd_meta.dev() {
return Err(DestDenyError::Toctou {
path: path.display().to_string(),
});
}
if fd_meta.nlink() > 1 {
let canon = std::fs::canonicalize(path).ok();
if hardlink_sibling_denied(path, canon.as_deref(), policy) {
return Err(DestDenyError::LateHardlink {
path: path.display().to_string(),
});
}
}
Ok(())
}
#[cfg(windows)]
fn verify_post_open_windows(
path: &Path,
fd: &File,
policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
use std::os::windows::io::AsRawHandle;
let path_info = win_path_by_handle(path)
.map_err(|e| DestDenyError::ToctouStat(format!("cannot stat {}: {e}", path.display())))?;
let fd_info = win_handle_info(fd.as_raw_handle())
.map_err(|e| DestDenyError::ToctouStat(format!("cannot fstat fd: {e}")))?;
if path_info.index != fd_info.index || path_info.volume != fd_info.volume {
return Err(DestDenyError::Toctou {
path: path.display().to_string(),
});
}
if fd_info.nlink > 1 {
let canon = std::fs::canonicalize(path).ok();
if hardlink_sibling_denied(path, canon.as_deref(), policy) {
return Err(DestDenyError::LateHardlink {
path: path.display().to_string(),
});
}
}
Ok(())
}
pub fn deny_patch_dests(
dests: &[impl AsRef<Path>],
policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
for dest in dests {
let dest = dest.as_ref();
if let Some(deny) = dest_deny_at(dest, dest.display().to_string(), policy) {
return Err(DestDenyError::Denied(deny));
}
}
Ok(())
}
pub fn deny_patch_dests_with_display(
dests: &[(&Path, &str)],
policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
for (dest, display) in dests {
if let Some(deny) = dest_deny_at(dest, (*display).to_owned(), policy) {
return Err(DestDenyError::Denied(deny));
}
}
Ok(())
}
pub fn reject_command_secret_path_tokens(
command: &str,
policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
for (display, candidate) in command_path_tokens(command) {
if candidate_is_denied(&candidate, policy) {
return Err(DestDenyError::CommandToken { token: display });
}
}
Ok(())
}
pub fn dest_under_root(root: &Path, path: &str) -> PathBuf {
let p = Path::new(path);
if p.is_absolute() {
p.to_path_buf()
} else {
root.join(p)
}
}
fn shell_c_body<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
let rest = token.strip_prefix('-')?;
if rest.starts_with('-') {
return None;
}
if is_shell_c_cluster(rest) {
return next;
}
let c_at = rest.find('c')?;
let prefix = rest.get(..=c_at)?;
if !is_shell_c_cluster(prefix) {
return None;
}
let after = rest.get(c_at + 1..)?;
if after.is_empty() {
return next;
}
Some(after)
}
fn is_shell_c_cluster(rest: &str) -> bool {
let len = rest.len();
if rest.eq_ignore_ascii_case("cwa") {
return false;
}
(1..=4).contains(&len) && rest.contains('c') && rest.chars().all(|ch| ch.is_ascii_alphabetic())
}
pub fn check_command_argv(
cmd: &[impl AsRef<str>],
root: &Path,
policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
for (i, token) in cmd.iter().enumerate() {
let token = token.as_ref();
if !token.is_empty() && !token.starts_with('-') {
let dest = dest_under_root(root, token);
check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
if let Some(value) = assignment_dest_value(token) {
let dest = dest_under_root(root, value);
check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
}
}
if let Some(value) = attached_flag_dest(token) {
let dest = dest_under_root(root, value);
check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
}
if let Some(body) = shell_c_body(token, cmd.get(i + 1).map(|s| s.as_ref())) {
check_command_dests(body, root, policy)?;
}
if is_cmd_program(token) || is_powershell_program(token) {
check_cmd_powershell_remaining_dests(token, &cmd[i + 1..], root, policy)?;
}
if is_env_program(token) {
check_env_flag_dests(&cmd[i + 1..], root, policy)?;
}
}
Ok(())
}
pub(crate) fn is_env_program(program: impl AsRef<OsStr>) -> bool {
let raw = program.as_ref().to_string_lossy();
let name = program_basename(&raw);
name.eq_ignore_ascii_case("env") || name.eq_ignore_ascii_case("env.exe")
}
fn program_basename(program: &str) -> &str {
program.rsplit(['/', '\\']).next().unwrap_or(program)
}
fn is_cmd_program(program: &str) -> bool {
let name = program_basename(program);
name.eq_ignore_ascii_case("cmd") || name.eq_ignore_ascii_case("cmd.exe")
}
fn is_powershell_program(program: &str) -> bool {
let name = program_basename(program);
name.eq_ignore_ascii_case("powershell")
|| name.eq_ignore_ascii_case("powershell.exe")
|| name.eq_ignore_ascii_case("pwsh")
|| name.eq_ignore_ascii_case("pwsh.exe")
}
fn cmd_script_body<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
let rest = token.strip_prefix('/')?;
let first = rest.chars().next()?;
if !matches!(first, 'c' | 'C' | 'k' | 'K') {
return None;
}
let after = rest.get(first.len_utf8()..)?;
if after.is_empty() {
return next;
}
Some(after)
}
fn strip_ps_switch(token: &str) -> Option<&str> {
let rest = token.strip_prefix(['-', '/'])?;
Some(rest.strip_prefix(['-', '/']).unwrap_or(rest))
}
fn powershell_command_body<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
let rest = strip_ps_switch(token)?;
if let Some((name, value)) = rest.split_once(':') {
if is_powershell_command_name(name) {
return Some(value);
}
return None;
}
if is_powershell_command_name(rest) {
return next;
}
None
}
fn powershell_encoded_payload<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
let rest = strip_ps_switch(token)?;
if let Some((name, value)) = rest.split_once(':') {
if is_powershell_encoded_command_name(name) {
return Some(value);
}
return None;
}
if is_powershell_encoded_command_name(rest) {
return next;
}
None
}
fn powershell_encoded_arguments_payload<'a>(
token: &'a str,
next: Option<&'a str>,
) -> Option<&'a str> {
let rest = strip_ps_switch(token)?;
if let Some((name, value)) = rest.split_once(':') {
if is_powershell_encoded_arguments_name(name) {
return Some(value);
}
return None;
}
if is_powershell_encoded_arguments_name(rest) {
return next;
}
None
}
fn is_powershell_encoded_command_name(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
lower == "encodedcommand"
|| lower == "enc"
|| lower == "ec"
|| lower == "e"
|| ("encodedcommand".starts_with(&lower)
&& !"erroraction".starts_with(&lower)
&& !"errorvariable".starts_with(&lower)
&& !"executionpolicy".starts_with(&lower))
}
fn powershell_file_dest<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
let rest = strip_ps_switch(token)?;
if let Some((name, value)) = rest.split_once(':') {
if is_powershell_file_name(name) {
return Some(value);
}
return None;
}
if is_powershell_file_name(rest) {
return next;
}
None
}
fn is_powershell_file_name(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
lower == "file" || lower == "f" || (lower.len() >= 2 && "file".starts_with(&lower))
}
fn is_powershell_command_name(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
lower == "command"
|| lower == "c"
|| (lower.len() >= 4 && "command".starts_with(&lower))
|| lower == "commandwithargs"
|| lower == "cwa"
|| (lower.len() >= 8 && "commandwithargs".starts_with(&lower))
}
fn is_powershell_encoded_arguments_name(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
lower == "encodedarguments"
|| lower == "ea"
|| ("encodedarguments".starts_with(&lower) && !"encodedcommand".starts_with(&lower))
}
fn check_cmd_powershell_remaining_dests(
program: &str,
rest: &[impl AsRef<str>],
root: &Path,
policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
if is_cmd_program(program) {
for (j, token) in rest.iter().enumerate() {
if let Some(body) = cmd_script_body(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
{
return check_command_dests(body, root, policy);
}
}
}
if is_powershell_program(program) {
for (j, token) in rest.iter().enumerate() {
if let Some(payload) =
powershell_encoded_payload(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
{
return check_powershell_encoded_dests(payload, root, policy);
}
if let Some(payload) = powershell_encoded_arguments_payload(
token.as_ref(),
rest.get(j + 1).map(|s| s.as_ref()),
) {
return check_powershell_encoded_dests(payload, root, policy);
}
if let Some(path) =
powershell_file_dest(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
{
refuse_powershell_stdin_dash(path)?;
let dest = dest_under_root(root, path);
return check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))
.map(|_| ());
}
if let Some(body) =
powershell_command_body(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
{
refuse_powershell_stdin_dash(body)?;
return check_command_dests(body, root, policy);
}
}
for token in rest {
if token.as_ref() == "-" {
return Err(DestDenyError::StdinScript.into());
}
}
}
Ok(())
}
fn refuse_powershell_stdin_dash(body: &str) -> Result<(), CheckDestError> {
if body == "-" {
return Err(DestDenyError::StdinScript.into());
}
Ok(())
}
fn check_powershell_encoded_dests(
payload: &str,
root: &Path,
policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
let script = decode_powershell_encoded_command(payload).ok_or(DestDenyError::EncodedCommand)?;
check_command_dests(&script, root, policy)
}
fn decode_powershell_encoded_command(payload: &str) -> Option<String> {
let stripped: String = payload
.chars()
.filter(|c| !matches!(*c, ' ' | '\t' | '\r' | '\n'))
.collect();
if stripped.is_empty() {
return None;
}
let bytes = decode_rfc4648_base64(stripped.as_bytes())?;
if bytes.len() % 2 != 0 {
return None;
}
let units: Vec<u16> = bytes
.chunks_exact(2)
.map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
.collect();
String::from_utf16(&units).ok()
}
fn decode_rfc4648_base64(input: &[u8]) -> Option<Vec<u8>> {
fn digit(b: u8) -> Option<u8> {
match b {
b'A'..=b'Z' => Some(b - b'A'),
b'a'..=b'z' => Some(b - b'a' + 26),
b'0'..=b'9' => Some(b - b'0' + 52),
b'+' => Some(62),
b'/' => Some(63),
_ => None,
}
}
let mut pad = 0usize;
let mut end = input.len();
while end > 0 && input[end - 1] == b'=' {
pad += 1;
end -= 1;
if pad > 2 {
return None;
}
}
if input[..end].contains(&b'=') {
return None;
}
if end % 4 == 1 {
return None;
}
let mut out = Vec::with_capacity(end * 3 / 4);
let mut acc: u32 = 0;
let mut bits: u32 = 0;
for &b in &input[..end] {
let v = u32::from(digit(b)?);
acc = (acc << 6) | v;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
acc &= (1 << bits) - 1;
}
}
if acc != 0 {
return None;
}
Some(out)
}
fn attached_flag_dest(token: &str) -> Option<&str> {
if !token.starts_with('-') || token == "-" || token == "--" {
return None;
}
if let Some((_, value)) = token.split_once('=') {
if value.is_empty() {
return None;
}
return Some(value);
}
if token.starts_with("--") {
return None;
}
let rest = token.get(1..)?;
let mut letters = 0usize;
for (i, ch) in rest.char_indices() {
if ch.is_ascii_alphabetic() {
letters += 1;
continue;
}
if letters == 0 {
return None;
}
let remainder = rest.get(i..)?;
if remainder.starts_with(['.', '/', '~']) {
return Some(remainder);
}
return None;
}
None
}
fn assignment_dest_value(token: &str) -> Option<&str> {
if token.is_empty() || token.starts_with('-') {
return None;
}
let (_, mut value) = token.split_once('=')?;
let bytes = value.as_bytes();
if bytes.len() >= 2 {
let quote = bytes[0];
if (quote == b'\'' || quote == b'"') && bytes[bytes.len() - 1] == quote {
value = &value[1..bytes.len() - 1];
}
}
if value.is_empty() { None } else { Some(value) }
}
#[cfg(feature = "nono")]
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum CmdWrapper {
Timeout,
Nohup,
Nice,
Time,
Stdbuf,
}
#[cfg(feature = "nono")]
pub(crate) fn cmd_wrapper(program: impl AsRef<OsStr>) -> Option<CmdWrapper> {
let raw = program.as_ref().to_string_lossy();
let name = raw.rsplit(['/', '\\']).next().unwrap_or(raw.as_ref());
if name.eq_ignore_ascii_case("timeout") || name.eq_ignore_ascii_case("timeout.exe") {
Some(CmdWrapper::Timeout)
} else if name.eq_ignore_ascii_case("nohup") || name.eq_ignore_ascii_case("nohup.exe") {
Some(CmdWrapper::Nohup)
} else if name.eq_ignore_ascii_case("nice") || name.eq_ignore_ascii_case("nice.exe") {
Some(CmdWrapper::Nice)
} else if name.eq_ignore_ascii_case("time") || name.eq_ignore_ascii_case("time.exe") {
Some(CmdWrapper::Time)
} else if name.eq_ignore_ascii_case("stdbuf") || name.eq_ignore_ascii_case("stdbuf.exe") {
Some(CmdWrapper::Stdbuf)
} else {
None
}
}
#[cfg(feature = "nono")]
pub(crate) fn skip_wrapper_prefix(kind: CmdWrapper, args: &[impl AsRef<str>]) -> usize {
let mut i = 0;
let mut options_done = false;
let mut skip_timeout_duration = kind == CmdWrapper::Timeout;
while i < args.len() {
let raw = args[i].as_ref();
if !options_done {
if raw == "--" {
options_done = true;
i += 1;
continue;
}
if let Some(skip) = wrapper_flag_skip(kind, raw) {
i = i.saturating_add(skip);
continue;
}
}
if skip_timeout_duration {
skip_timeout_duration = false;
i += 1;
continue;
}
return i;
}
i
}
#[cfg(feature = "nono")]
fn wrapper_takes_value(kind: CmdWrapper, flag: char) -> bool {
match kind {
CmdWrapper::Timeout => matches!(flag, 's' | 'k'),
CmdWrapper::Nice => flag == 'n',
CmdWrapper::Nohup | CmdWrapper::Time => false,
CmdWrapper::Stdbuf => matches!(flag, 'o' | 'e' | 'i'),
}
}
#[cfg(feature = "nono")]
fn wrapper_long_takes_value(kind: CmdWrapper, long: &str) -> bool {
match kind {
CmdWrapper::Timeout => matches!(long, "signal" | "kill-after"),
CmdWrapper::Nice => long == "adjustment",
CmdWrapper::Nohup | CmdWrapper::Time => false,
CmdWrapper::Stdbuf => matches!(long, "output" | "error" | "input"),
}
}
#[cfg(feature = "nono")]
fn wrapper_flag_skip(kind: CmdWrapper, arg: &str) -> Option<usize> {
if arg == "-" {
return Some(1);
}
if !arg.starts_with('-') {
return None;
}
if let Some(long) = arg.strip_prefix("--") {
if long.contains('=') {
return Some(1);
}
return Some(if wrapper_long_takes_value(kind, long) {
2
} else {
1
});
}
let mut chars = arg[1..].chars();
while let Some(c) = chars.next() {
if wrapper_takes_value(kind, c) {
return Some(if chars.next().is_some() { 1 } else { 2 });
}
}
Some(1)
}
pub(crate) fn env_takes_value(flag: char) -> bool {
matches!(flag, 'u' | 'C' | 'S' | 'P' | 'a' | 'f')
}
pub(crate) fn env_flag_skip(arg: &str) -> Option<usize> {
if arg == "-" {
return Some(1);
}
if !arg.starts_with('-') {
return None;
}
if let Some(long) = arg.strip_prefix("--") {
if long.contains('=') {
return Some(1);
}
return Some(match long {
"unset" | "split-string" | "chdir" | "argv0" | "file" => 2,
_ => 1,
});
}
let mut chars = arg[1..].chars();
while let Some(c) = chars.next() {
if env_takes_value(c) {
return Some(if chars.next().is_some() { 1 } else { 2 });
}
}
Some(1)
}
fn check_env_flag_dests(
args: &[impl AsRef<str>],
root: &Path,
policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
check_env_flag_dests_inner(args, root, policy, false)
}
fn check_env_split_string_dests(
operand: &str,
root: &Path,
policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
check_command_dests(operand, root, policy)?;
let leftover: Vec<&str> = operand.split_whitespace().collect();
check_env_flag_dests_inner(&leftover, root, policy, true)
}
fn check_env_flag_dests_inner(
args: &[impl AsRef<str>],
root: &Path,
policy: &DenyPolicy,
deny_assign_values: bool,
) -> Result<(), CheckDestError> {
let mut i = 0;
while i < args.len() {
let raw = args[i].as_ref();
if raw == "--" || raw == "-" {
return continue_env_after_operand(&args[i + 1..], root, policy);
}
if !raw.starts_with('-') {
if raw.contains('=') {
if deny_assign_values
&& let Some((_, value)) = raw.split_once('=')
&& !value.is_empty()
{
check_env_file_dest(value, root, policy)?;
}
i += 1;
continue;
}
return continue_env_after_operand(&args[i..], root, policy);
}
if let Some(long) = raw.strip_prefix("--") {
if let Some((name, value)) = long.split_once('=') {
check_env_named_operand(name, value, root, policy)?;
i += 1;
continue;
}
let next = args.get(i + 1).map(|s| s.as_ref());
match long {
"split-string" | "file" | "unset" | "chdir" | "argv0" => {
if let Some(next) = next {
check_env_named_operand(long, next, root, policy)?;
}
i += 2;
}
_ => i += 1,
}
continue;
}
let mut chars = raw[1..].chars();
let mut value_flag = None;
let mut attached = String::new();
while let Some(c) = chars.next() {
if env_takes_value(c) {
value_flag = Some(c);
attached = chars.collect();
break;
}
}
match value_flag {
Some(flag) => {
let operand = if attached.is_empty() {
args.get(i + 1).map(|s| s.as_ref())
} else {
Some(attached.as_str())
};
if let Some(operand) = operand {
match flag {
'S' => check_env_split_string_dests(operand, root, policy)?,
'f' => check_env_file_dest(operand, root, policy)?,
_ => {}
}
}
i += if attached.is_empty() { 2 } else { 1 };
}
None => i += 1,
}
}
Ok(())
}
fn continue_env_after_operand(
args: &[impl AsRef<str>],
root: &Path,
policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
for (i, token) in args.iter().enumerate() {
if is_env_program(token.as_ref()) {
return check_env_flag_dests(&args[i + 1..], root, policy);
}
}
Ok(())
}
fn check_env_named_operand(
name: &str,
value: &str,
root: &Path,
policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
match name {
"split-string" => check_env_split_string_dests(value, root, policy),
"file" => check_env_file_dest(value, root, policy),
_ => Ok(()),
}
}
fn check_env_file_dest(path: &str, root: &Path, policy: &DenyPolicy) -> Result<(), CheckDestError> {
let dest = dest_under_root(root, path);
check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root)).map(|_| ())
}
pub fn check_command_dests(
command: &str,
root: &Path,
policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
for (_display, candidate) in command_path_tokens(command) {
for peeled in peel_shell_parts(&candidate) {
if peeled.is_empty() {
continue;
}
if let Some(value) = attached_flag_dest(peeled) {
let dest = dest_under_root(root, value);
check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
continue;
}
if peeled.starts_with('-') {
continue;
}
let dest = dest_under_root(root, peeled);
check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
if let Some(value) = assignment_dest_value(peeled) {
let dest = dest_under_root(root, value);
check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
}
}
}
check_command_string_env_dests(command, root, policy)
}
fn check_command_string_env_dests(
command: &str,
root: &Path,
policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
for part in peel_shell_parts(command) {
let tokens = command_string_tokens(part);
for (i, token) in tokens.iter().enumerate() {
if is_env_program(*token) {
check_env_flag_dests(&tokens[i + 1..], root, policy)?;
}
if let Some(body) = shell_c_body(token, tokens.get(i + 1).copied()) {
check_command_string_env_dests(body, root, policy)?;
}
if is_cmd_program(token) || is_powershell_program(token) {
check_cmd_powershell_remaining_dests(token, &tokens[i + 1..], root, policy)?;
}
}
}
Ok(())
}
fn command_string_tokens(command: &str) -> Vec<&str> {
let bytes = command.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
if bytes[i].is_ascii_whitespace() {
i += 1;
continue;
}
if bytes[i] == b'\'' || bytes[i] == b'"' {
let q = bytes[i];
i += 1;
let start = i;
while i < bytes.len() && bytes[i] != q {
i += 1;
}
out.push(&command[start..i]);
if i < bytes.len() {
i += 1;
}
continue;
}
let start = i;
while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
i += 1;
}
out.push(&command[start..i]);
}
out
}
pub fn is_env_template_basename(name: &str) -> bool {
let base = name
.rsplit(['/', '\\'])
.next()
.unwrap_or(name)
.to_ascii_lowercase();
base.starts_with(".env.")
&& (base.ends_with(".example") || base.ends_with(".sample") || base.ends_with(".template"))
}
pub fn validate_deny_glob(glob: &str) -> Result<(), &'static str> {
let glob = glob.trim();
if glob.is_empty() {
return Err("empty dest-deny glob");
}
if glob.contains('{') || glob.contains('}') {
return Err("brace alternation is not supported");
}
if glob.contains('\\') {
return Err("backslash escapes are not supported");
}
let normalized = normalize_glob_text(glob);
let segs: Vec<&str> = normalized.split('/').collect();
if segs.iter().any(|s| s.is_empty()) {
return Err("empty path segment");
}
if segs.iter().any(|s| *s == "." || *s == "..") {
return Err("'.' / '..' path segment");
}
Ok(())
}
pub fn dest_deny_glob_regex(prefix: &str, glob: &str) -> Option<String> {
validate_deny_glob(glob).ok()?;
let mut glob = glob.trim();
if glob.is_empty() {
return None;
}
let nested = glob.starts_with("**/");
if nested {
glob = glob.strip_prefix("**/")?;
}
let trailing_dir = glob.ends_with("/**");
if trailing_dir {
glob = glob.strip_suffix("/**")?;
}
if glob.is_empty() {
return None;
}
let mut body = String::new();
let chars: Vec<char> = glob.chars().collect();
let mut i = 0;
while i < chars.len() {
if chars[i] == '*' {
if i + 1 < chars.len() && chars[i + 1] == '*' {
body.push_str("(.*/)?");
i += 2;
if i < chars.len() && chars[i] == '/' {
i += 1;
}
continue;
}
body.push_str("[^/]*");
i += 1;
continue;
}
if matches!(
chars[i],
'.' | '+' | '?' | '(' | ')' | '[' | ']' | '|' | '^' | '$'
) {
body.push('\\');
body.push(chars[i]);
i += 1;
continue;
}
push_ascii_letter_class(&mut body, chars[i]);
i += 1;
}
if trailing_dir {
body.push_str("(/.*)?");
}
let prefix = case_fold_regex_letters(prefix);
if nested {
Some(format!("^{prefix}/(.*/)?{body}$"))
} else {
Some(format!("^{prefix}/{body}$"))
}
}
fn push_ascii_letter_class(out: &mut String, c: char) {
if c.is_ascii_alphabetic() {
out.push('[');
out.push(c.to_ascii_uppercase());
out.push(c.to_ascii_lowercase());
out.push(']');
} else {
out.push(c);
}
}
fn case_fold_regex_letters(s: &str) -> String {
let mut out = String::new();
let mut escaped = false;
for c in s.chars() {
if escaped {
out.push(c);
escaped = false;
continue;
}
if c == '\\' {
out.push('\\');
escaped = true;
continue;
}
push_ascii_letter_class(&mut out, c);
}
out
}
pub fn path_matches_deny_glob(pattern: &str, path: &str) -> bool {
let pattern = normalize_glob_text(pattern);
let path = windows_secret_spelling(&normalize_glob_text(path));
let pat: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
match_glob_segments(&pat, &segs)
}
fn windows_secret_spelling(path: &str) -> String {
#[cfg(windows)]
{
if path.starts_with("//?/") {
return path.to_string();
}
let (dir, name) = match path.rfind('/') {
Some(i) => (&path[..=i], &path[i + 1..]),
None => ("", path),
};
let name = name.trim_end_matches([' ', '.']);
let name = name.split(':').next().unwrap_or(name);
let name = name.trim_end_matches([' ', '.']);
if name.is_empty() {
return path.to_string();
}
format!("{dir}{name}")
}
#[cfg(not(windows))]
{
path.to_string()
}
}
pub fn path_is_denied_glob(globs: &[String], path: &str) -> bool {
first_matching_deny_glob(globs, path).is_some()
}
fn first_matching_deny_glob(globs: &[String], path: &str) -> Option<String> {
deny_glob_name(first_matching_deny_glob_under(globs, path, None))
}
fn deny_glob_name(glob: Option<String>) -> Option<String> {
glob.filter(|name| name != "..")
}
pub fn path_is_denied_under_root(globs: &[String], path: &str, root: &Path) -> bool {
first_matching_deny_glob_under(globs, path, Some(root)).is_some()
}
fn first_matching_deny_glob_under(
globs: &[String],
path: &str,
root: Option<&Path>,
) -> Option<String> {
let Some(root) = root else {
return first_matching_deny_glob_unscoped(globs, path);
};
let had_dotdot = path.split(['/', '\\']).any(|seg| seg == "..");
let Some(collapsed) = lexical_absolute(path) else {
return Some("..".to_string());
};
let (match_path, outside) = match strip_workspace_root(&collapsed, root) {
Some(rel) => (rel, false),
None if had_dotdot => return Some("..".to_string()),
None => (collapsed, true),
};
let template = is_env_template_basename(&match_path);
let base = match_path.rsplit('/').next().unwrap_or(match_path.as_str());
globs
.iter()
.find(|g| {
if template && is_default_env_star_glob(g) {
return false;
}
let slashed = normalize_glob_text(g).contains('/');
if outside && slashed && !normalize_glob_text(g).starts_with("**/") {
return false;
}
if path_matches_deny_glob(g, &match_path) {
return true;
}
!slashed && path_matches_deny_glob(g, base)
})
.cloned()
}
fn lexical_absolute(path: &str) -> Option<String> {
let norm = normalize_glob_text(path);
let absolute = norm.starts_with('/');
let mut segs = Vec::new();
for seg in norm.split('/') {
if seg.is_empty() || seg == "." {
continue;
}
if seg == ".." {
let _ = segs.pop();
continue;
}
segs.push(seg);
}
if absolute {
Some(format!("/{}", segs.join("/")))
} else {
Some(segs.join("/"))
}
}
fn strip_workspace_root(path: &str, root: &Path) -> Option<String> {
let path_segs = lexical_absolute(path)?;
for spelling in firmlink_spellings(root) {
let Some(root_s) = lexical_absolute(&path_as_glob(&spelling)) else {
continue;
};
if let Some(rel) = strip_prefix_path(&path_segs, &root_s) {
return Some(rel);
}
}
None
}
fn strip_prefix_path(path: &str, root: &str) -> Option<String> {
let path = path.trim_end_matches('/');
let root = root.trim_end_matches('/');
if path.eq_ignore_ascii_case(root) {
return Some(String::new());
}
let prefix = format!("{root}/");
if path.len() >= prefix.len()
&& path.is_char_boundary(prefix.len())
&& path[..prefix.len()].eq_ignore_ascii_case(&prefix)
{
return Some(path[prefix.len()..].to_string());
}
None
}
fn firmlink_spellings(path: &Path) -> Vec<PathBuf> {
let mut out = vec![path.to_path_buf()];
if let Some(alias) = firmlink_alias_path(path)
&& !out.iter().any(|p| p == &alias)
{
out.push(alias);
}
out
}
fn firmlink_alias_path(path: &Path) -> Option<PathBuf> {
let raw = path.to_str()?.replace('\\', "/");
const PAIRS: [(&str, &str); 3] = [
("/tmp", "/private/tmp"),
("/var", "/private/var"),
("/etc", "/private/etc"),
];
for (public, private) in PAIRS {
if raw == public || raw.starts_with(&format!("{public}/")) {
return Some(PathBuf::from(format!(
"{private}{}",
raw.strip_prefix(public).unwrap_or("")
)));
}
if raw == private || raw.starts_with(&format!("{private}/")) {
return Some(PathBuf::from(format!(
"{public}{}",
raw.strip_prefix(private).unwrap_or("")
)));
}
}
None
}
pub(crate) fn first_matching_deny_glob_unscoped(globs: &[String], path: &str) -> Option<String> {
let template = is_env_template_basename(path);
let base = path.rsplit(['/', '\\']).next().unwrap_or(path);
globs
.iter()
.find(|g| {
if template && is_default_env_star_glob(g) {
return false;
}
let slashed = normalize_glob_text(g).contains('/');
path_matches_deny_glob(g, path) || (!slashed && path_matches_deny_glob(g, base))
})
.cloned()
}
pub(crate) fn is_default_env_star_glob(pattern: &str) -> bool {
normalize_glob_text(pattern) == "**/.env.*"
}
fn path_as_glob(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
fn normalize_glob_text(s: &str) -> String {
s.replace('\\', "/").to_ascii_lowercase()
}
fn match_glob_segments(pat: &[&str], path: &[&str]) -> bool {
let mut memo = vec![None; (pat.len() + 1) * (path.len() + 1)];
match_glob_at(pat, path, &mut memo, 0, 0)
}
fn match_glob_at(
pat: &[&str],
path: &[&str],
memo: &mut [Option<bool>],
pat_i: usize,
path_i: usize,
) -> bool {
let slot = pat_i * (path.len() + 1) + path_i;
if let Some(done) = memo[slot] {
return done;
}
let matched = match pat.get(pat_i) {
None => path_i == path.len(),
Some(&"**") => {
if pat_i + 1 == pat.len() {
true
} else {
(path_i..=path.len()).any(|next| match_glob_at(pat, path, memo, pat_i + 1, next))
}
}
Some(segment) => {
path_i < path.len()
&& glob_segment(segment, path[path_i])
&& match_glob_at(pat, path, memo, pat_i + 1, path_i + 1)
}
};
memo[slot] = Some(matched);
matched
}
fn glob_segment(pat: &str, text: &str) -> bool {
match_star(pat.as_bytes(), text.as_bytes())
}
fn match_star(pat: &[u8], text: &[u8]) -> bool {
let mut pat_i = 0;
let mut text_i = 0;
let mut star_pat: Option<usize> = None;
let mut star_text = 0;
while text_i < text.len() {
if pat_i < pat.len() && pat[pat_i] == b'*' {
star_pat = Some(pat_i);
star_text = text_i;
pat_i += 1;
} else if pat_i < pat.len() && pat[pat_i] == text[text_i] {
pat_i += 1;
text_i += 1;
} else if let Some(saved) = star_pat {
star_text += 1;
text_i = star_text;
pat_i = saved + 1;
} else {
return false;
}
}
while pat_i < pat.len() && pat[pat_i] == b'*' {
pat_i += 1;
}
pat_i == pat.len()
}
#[derive(Debug)]
enum HardlinkHit {
Allowed,
Denied { sibling: Option<String> },
}
fn denied_basename_rank(
globs: &[String],
path: &Path,
root: Option<&Path>,
) -> Option<(usize, String)> {
let glob = first_matching_deny_glob_under(globs, &path_as_glob(path), root)?;
if glob == ".." {
return None;
}
let idx = globs
.iter()
.position(|candidate| candidate == &glob)
.unwrap_or(usize::MAX);
let base = path.file_name()?.to_string_lossy().into_owned();
Some((idx, base))
}
fn prefer_sibling(best: Option<(usize, String)>, next: (usize, String)) -> Option<(usize, String)> {
match best {
None => Some(next),
Some((idx, name)) if next.0 < idx || (next.0 == idx && next.1 < name) => Some(next),
Some(kept) => Some(kept),
}
}
fn hardlink_sibling_denied(path: &Path, canon: Option<&Path>, policy: &DenyPolicy) -> bool {
matches!(
hardlink_sibling_hit(path, canon, policy, None),
HardlinkHit::Denied { .. }
)
}
fn hardlink_sibling_hit(
path: &Path,
canon: Option<&Path>,
policy: &DenyPolicy,
root: Option<&Path>,
) -> HardlinkHit {
#[cfg(unix)]
{
hardlink_sibling_hit_unix(path, canon, policy, root)
}
#[cfg(windows)]
{
hardlink_sibling_hit_windows(path, canon, policy, root)
}
#[cfg(not(any(unix, windows)))]
{
let _ = (path, canon, policy, root);
HardlinkHit::Allowed
}
}
#[cfg(unix)]
#[derive(Clone)]
struct SiblingSeen {
dev: u64,
ino: u64,
path: PathBuf,
}
#[cfg(unix)]
#[derive(Clone)]
enum ParentScan {
Entries(Vec<SiblingSeen>),
Unreadable,
}
#[cfg(unix)]
enum ParentStep {
Next,
Break,
Deny,
}
#[cfg(unix)]
struct ParentFold {
step: ParentStep,
found_add: u64,
best: Option<(usize, String)>,
}
#[cfg(unix)]
thread_local! {
static HARDLINK_SCAN_DEPTH: Cell<u32> = const { Cell::new(0) };
static HARDLINK_PARENT_SCANS: RefCell<Option<HashMap<PathBuf, ParentScan>>> =
const { RefCell::new(None) };
static HARDLINK_DIR_READS: Cell<u32> = const { Cell::new(0) };
#[cfg(test)]
static TEST_LINK_DIRS: RefCell<Vec<PathBuf>> = const { RefCell::new(Vec::new()) };
}
#[cfg(unix)]
pub(crate) struct HardlinkScanScope;
#[cfg(unix)]
impl HardlinkScanScope {
pub(crate) fn new() -> Self {
HARDLINK_SCAN_DEPTH.with(|depth| {
if depth.get() == 0 {
HARDLINK_PARENT_SCANS.with(|scans| *scans.borrow_mut() = Some(HashMap::new()));
}
depth.set(depth.get() + 1);
});
Self
}
}
#[cfg(unix)]
impl Drop for HardlinkScanScope {
fn drop(&mut self) {
HARDLINK_SCAN_DEPTH.with(|depth| {
let next = depth.get().saturating_sub(1);
depth.set(next);
if next == 0 {
HARDLINK_PARENT_SCANS.with(|scans| *scans.borrow_mut() = None);
}
});
}
}
#[cfg(unix)]
fn note_hardlink_dir_read() {
HARDLINK_DIR_READS.with(|n| n.set(n.get().saturating_add(1)));
}
#[cfg(all(unix, test))]
fn reset_hardlink_dir_reads() {
HARDLINK_DIR_READS.with(|n| n.set(0));
}
#[cfg(all(unix, test))]
fn hardlink_dir_reads() -> u32 {
HARDLINK_DIR_READS.with(|n| n.get())
}
#[cfg(unix)]
fn read_parent_siblings(parent: &Path) -> ParentScan {
use std::os::unix::fs::MetadataExt;
note_hardlink_dir_read();
let entries = match std::fs::read_dir(parent) {
Ok(rd) => rd,
Err(_) => return ParentScan::Unreadable,
};
let mut seen = Vec::new();
for entry in entries.flatten() {
let entry_path = entry.path();
let sibling_meta = match std::fs::symlink_metadata(&entry_path) {
Ok(meta) => meta,
Err(_) => continue,
};
if sibling_meta.file_type().is_dir() {
continue;
}
seen.push(SiblingSeen {
dev: sibling_meta.dev(),
ino: sibling_meta.ino(),
path: entry_path,
});
}
ParentScan::Entries(seen)
}
#[cfg(unix)]
fn with_parent_siblings<R>(parent: &Path, f: impl FnOnce(&ParentScan) -> R) -> R {
let in_scope = HARDLINK_PARENT_SCANS.with(|slot| slot.borrow().is_some());
if !in_scope {
let scan = read_parent_siblings(parent);
return f(&scan);
}
let hit = HARDLINK_PARENT_SCANS.with(|slot| {
slot.borrow()
.as_ref()
.is_some_and(|map| map.contains_key(parent))
});
if hit {
return HARDLINK_PARENT_SCANS.with(|slot| {
let borrowed = slot.borrow();
let scan = borrowed
.as_ref()
.and_then(|map| map.get(parent))
.unwrap_or(&ParentScan::Unreadable);
f(scan)
});
}
let scan = read_parent_siblings(parent);
let result = f(&scan);
HARDLINK_PARENT_SCANS.with(|slot| {
if let Some(map) = slot.borrow_mut().as_mut() {
map.insert(parent.to_path_buf(), scan);
}
});
result
}
#[cfg(unix)]
fn hardlink_sibling_hit_unix(
path: &Path,
canon: Option<&Path>,
policy: &DenyPolicy,
root: Option<&Path>,
) -> HardlinkHit {
use std::os::unix::fs::MetadataExt;
let meta = match canon
.map(std::fs::metadata)
.unwrap_or_else(|| std::fs::symlink_metadata(path))
{
Ok(m) => m,
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
return HardlinkHit::Denied { sibling: None };
}
Err(_) => return HardlinkHit::Allowed,
};
if meta.file_type().is_dir() {
return HardlinkHit::Allowed;
}
let nlink = meta.nlink();
if nlink <= 1 {
return HardlinkHit::Allowed;
}
let mut parents = Vec::new();
push_scan_parent(&mut parents, path.parent());
if let Some(c) = canon {
push_scan_parent(&mut parents, c.parent());
}
if parents.is_empty() {
return HardlinkHit::Denied { sibling: None };
}
let mut found = 0u64;
let mut best: Option<(usize, String)> = None;
for parent in &parents {
let folded = fold_link_parent(parent, meta.dev(), meta.ino(), policy, root, best, true);
found += folded.found_add;
best = folded.best;
match folded.step {
ParentStep::Next => {}
ParentStep::Break => break,
ParentStep::Deny => return HardlinkHit::Denied { sibling: None },
}
}
if let Some((_, sibling)) = best {
return HardlinkHit::Denied {
sibling: Some(sibling),
};
}
if found < nlink {
for parent in extra_link_dirs() {
let key = std::fs::canonicalize(&parent).unwrap_or(parent);
if parents.iter().any(|seen| seen == &key) {
continue;
}
parents.push(key.clone());
let folded = fold_link_parent(&key, meta.dev(), meta.ino(), policy, root, best, false);
found += folded.found_add;
best = folded.best;
if best.is_some() || found >= nlink {
break;
}
}
}
if let Some((_, sibling)) = best {
return HardlinkHit::Denied {
sibling: Some(sibling),
};
}
if found < nlink {
HardlinkHit::Denied { sibling: None }
} else {
HardlinkHit::Allowed
}
}
#[cfg(unix)]
fn extra_link_dirs() -> Vec<PathBuf> {
#[cfg(test)]
{
let hooked = TEST_LINK_DIRS.with(|dirs| dirs.borrow().clone());
if !hooked.is_empty() {
return hooked;
}
}
let mut dirs = Vec::new();
if let Some(path) = std::env::var_os("PATH") {
dirs.extend(std::env::split_paths(&path));
}
for extra in [
"/bin",
"/usr/bin",
"/usr/lib/cargo/bin",
"/usr/lib/cargo/bin/coreutils",
] {
dirs.push(PathBuf::from(extra));
}
dirs
}
#[cfg(unix)]
fn fold_link_parent(
parent: &Path,
dev: u64,
ino: u64,
policy: &DenyPolicy,
root: Option<&Path>,
best: Option<(usize, String)>,
missing_denies: bool,
) -> ParentFold {
with_parent_siblings(parent, |scan| match scan {
ParentScan::Unreadable => {
let step = if missing_denies && best.is_none() {
ParentStep::Deny
} else if missing_denies {
ParentStep::Break
} else {
ParentStep::Next
};
ParentFold {
step,
found_add: 0,
best,
}
}
ParentScan::Entries(entries) => {
let mut found_add = 0u64;
let mut best = best;
for sibling in entries {
if sibling.dev != dev || sibling.ino != ino {
continue;
}
found_add += 1;
if let Some(rank) = denied_basename_rank(policy.globs(), &sibling.path, root) {
best = prefer_sibling(best, rank);
}
}
ParentFold {
step: ParentStep::Next,
found_add,
best,
}
}
})
}
#[cfg(unix)]
fn push_scan_parent(parents: &mut Vec<PathBuf>, parent: Option<&Path>) {
let parent = match parent {
Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
Some(_) => PathBuf::from("."),
None => return,
};
let key = std::fs::canonicalize(&parent).unwrap_or(parent);
if !parents.iter().any(|p| p == &key) {
parents.push(key);
}
}
#[cfg(any(windows, test))]
const WIN_ERROR_NO_MORE_FILES: u32 = 18;
#[cfg(any(windows, test))]
const WIN_ERROR_HANDLE_EOF: u32 = 38;
#[cfg(any(windows, test))]
fn win_find_next_exhausted(err: u32) -> bool {
err == WIN_ERROR_NO_MORE_FILES || err == WIN_ERROR_HANDLE_EOF
}
#[cfg(any(windows, test))]
fn hardlink_hit_from_win_names(
names: &[std::ffi::OsString],
nlink: u32,
policy: &DenyPolicy,
root: Option<&Path>,
) -> HardlinkHit {
if names.len() < nlink as usize {
return HardlinkHit::Denied { sibling: None };
}
if names.len() <= 1 {
return HardlinkHit::Allowed;
}
let mut best: Option<(usize, String)> = None;
for n in names {
let s = n.to_string_lossy().replace('\\', "/");
if let Some(rank) = denied_basename_rank(policy.globs(), Path::new(&s), root) {
best = prefer_sibling(best, rank);
}
}
if let Some((_, sibling)) = best {
return HardlinkHit::Denied {
sibling: Some(sibling),
};
}
HardlinkHit::Allowed
}
#[cfg(windows)]
fn hardlink_sibling_hit_windows(
path: &Path,
canon: Option<&Path>,
policy: &DenyPolicy,
root: Option<&Path>,
) -> HardlinkHit {
let probe = canon.unwrap_or(path);
let meta = match std::fs::metadata(probe) {
Ok(m) => m,
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
return HardlinkHit::Denied { sibling: None };
}
Err(_) => return HardlinkHit::Allowed,
};
if meta.is_dir() {
return HardlinkHit::Allowed;
}
let nlink = match win_path_by_handle(probe) {
Ok(info) => info.nlink,
Err(_) => return HardlinkHit::Denied { sibling: None },
};
match win_hardlink_names(probe) {
Ok(names) => hardlink_hit_from_win_names(&names, nlink, policy, root),
Err(_) => HardlinkHit::Denied { sibling: None },
}
}
#[cfg(windows)]
fn win_hardlink_names(path: &Path) -> std::io::Result<Vec<std::ffi::OsString>> {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
type Handle = *mut core::ffi::c_void;
type Dword = u32;
const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;
const ERROR_MORE_DATA: Dword = 234;
#[link(name = "kernel32")]
unsafe extern "system" {
fn FindFirstFileNameW(
lp_file_name: *const u16,
dw_flags: Dword,
string_length: *mut Dword,
link_name: *mut u16,
) -> Handle;
fn FindNextFileNameW(
h_find_stream: Handle,
string_length: *mut Dword,
link_name: *mut u16,
) -> i32;
fn FindClose(h_find_file: Handle) -> i32;
fn GetLastError() -> Dword;
}
struct FindNameHandle(Handle);
impl Drop for FindNameHandle {
fn drop(&mut self) {
if self.0 != INVALID_HANDLE_VALUE {
unsafe {
FindClose(self.0);
}
self.0 = INVALID_HANDLE_VALUE;
}
}
}
fn wide_to_os(buf: &[u16], claimed: usize) -> std::ffi::OsString {
let end = buf
.iter()
.position(|&c| c == 0)
.unwrap_or(claimed.min(buf.len()));
std::ffi::OsString::from_wide(&buf[..end])
}
let wide: Vec<u16> = path
.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect();
let mut len: Dword = 256;
let mut buf = vec![0u16; 256];
let handle = loop {
let h = unsafe { FindFirstFileNameW(wide.as_ptr(), 0, &mut len, buf.as_mut_ptr()) };
if h != INVALID_HANDLE_VALUE {
break FindNameHandle(h);
}
let err = unsafe { GetLastError() };
if err == ERROR_MORE_DATA {
buf.resize(len as usize, 0);
continue;
}
return Err(std::io::Error::from_raw_os_error(err as i32));
};
let mut names = vec![wide_to_os(&buf, len as usize)];
loop {
len = buf.len() as Dword;
let ok = unsafe { FindNextFileNameW(handle.0, &mut len, buf.as_mut_ptr()) };
if ok == 0 {
let err = unsafe { GetLastError() };
if err == ERROR_MORE_DATA {
buf.resize(len as usize, 0);
continue;
}
if win_find_next_exhausted(err) {
break;
}
return Err(std::io::Error::from_raw_os_error(err as i32));
}
names.push(wide_to_os(&buf, len as usize));
}
Ok(names)
}
#[cfg(windows)]
struct WinHandleInfo {
volume: u32,
index: u64,
nlink: u32,
}
#[cfg(windows)]
fn win_path_by_handle(path: &Path) -> std::io::Result<WinHandleInfo> {
use std::os::windows::ffi::OsStrExt;
type Handle = *mut core::ffi::c_void;
type Dword = u32;
const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;
const FILE_READ_ATTRIBUTES: Dword = 0x0080;
const FILE_SHARE_READ: Dword = 0x0001;
const FILE_SHARE_WRITE: Dword = 0x0002;
const FILE_SHARE_DELETE: Dword = 0x0004;
const OPEN_EXISTING: Dword = 3;
const FILE_FLAG_BACKUP_SEMANTICS: Dword = 0x0200_0000;
const FILE_FLAG_OPEN_REPARSE_POINT: Dword = 0x0020_0000;
#[link(name = "kernel32")]
unsafe extern "system" {
fn CreateFileW(
lp_file_name: *const u16,
dw_desired_access: Dword,
dw_share_mode: Dword,
lp_security_attributes: *mut core::ffi::c_void,
dw_creation_disposition: Dword,
dw_flags_and_attributes: Dword,
h_template_file: Handle,
) -> Handle;
fn CloseHandle(h_object: Handle) -> i32;
fn GetLastError() -> Dword;
}
let wide: Vec<u16> = path
.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect();
let handle = unsafe {
CreateFileW(
wide.as_ptr(),
FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
core::ptr::null_mut(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
core::ptr::null_mut(),
)
};
if handle == INVALID_HANDLE_VALUE {
let err = unsafe { GetLastError() };
return Err(std::io::Error::from_raw_os_error(err as i32));
}
let info = win_handle_info(handle);
unsafe {
CloseHandle(handle);
}
info
}
#[cfg(windows)]
fn win_handle_info(handle: *mut core::ffi::c_void) -> std::io::Result<WinHandleInfo> {
type Dword = u32;
#[repr(C)]
struct ByHandleFileInformation {
dw_file_attributes: Dword,
ft_creation_time_lo: Dword,
ft_creation_time_hi: Dword,
ft_last_access_time_lo: Dword,
ft_last_access_time_hi: Dword,
ft_last_write_time_lo: Dword,
ft_last_write_time_hi: Dword,
dw_volume_serial_number: Dword,
n_file_size_high: Dword,
n_file_size_low: Dword,
n_number_of_links: Dword,
n_file_index_high: Dword,
n_file_index_low: Dword,
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetFileInformationByHandle(
h_file: *mut core::ffi::c_void,
lp_file_information: *mut ByHandleFileInformation,
) -> i32;
fn GetLastError() -> Dword;
}
let mut info = ByHandleFileInformation {
dw_file_attributes: 0,
ft_creation_time_lo: 0,
ft_creation_time_hi: 0,
ft_last_access_time_lo: 0,
ft_last_access_time_hi: 0,
ft_last_write_time_lo: 0,
ft_last_write_time_hi: 0,
dw_volume_serial_number: 0,
n_file_size_high: 0,
n_file_size_low: 0,
n_number_of_links: 0,
n_file_index_high: 0,
n_file_index_low: 0,
};
let ok = unsafe { GetFileInformationByHandle(handle, &mut info) };
if ok == 0 {
let err = unsafe { GetLastError() };
return Err(std::io::Error::from_raw_os_error(err as i32));
}
Ok(WinHandleInfo {
volume: info.dw_volume_serial_number,
index: (u64::from(info.n_file_index_high) << 32) | u64::from(info.n_file_index_low),
nlink: info.n_number_of_links,
})
}
fn peel_shell_meta(s: &str) -> &str {
s.trim_matches(|c: char| matches!(c, ';' | '|' | '&' | ')' | '(' | '<' | '>' | '`' | ','))
}
fn peel_shell_parts(s: &str) -> impl Iterator<Item = &str> {
s.split([';', '|', '&', ')', '(', '<', '>', '`', ','])
.map(peel_shell_meta)
.filter(|p| !p.is_empty())
}
fn candidate_is_denied(candidate: &str, policy: &DenyPolicy) -> bool {
for peeled in peel_shell_parts(candidate) {
if peeled.starts_with('-') {
continue;
}
if is_path_denied(Path::new(peeled), policy) {
return true;
}
if let Some(value) = assignment_dest_value(peeled)
&& is_path_denied(Path::new(value), policy)
{
return true;
}
if let Some((_, after)) = peeled.rsplit_once(':') {
let after = peel_shell_meta(after);
if !after.is_empty()
&& !after.starts_with('-')
&& is_path_denied(Path::new(after), policy)
{
return true;
}
}
}
false
}
fn command_path_tokens(command: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
collect_function_calls(command, &mut out);
collect_quoted_and_words(command, &mut out);
out
}
fn collect_function_calls(s: &str, out: &mut Vec<(String, String)>) {
let mut pos = 0;
while let Some((end, display, path)) = next_function_call(s, pos) {
out.push((display, path));
pos = end;
}
}
fn next_function_call(s: &str, from: usize) -> Option<(usize, String, String)> {
let bytes = s.as_bytes();
let mut i = from;
while i < bytes.len() {
if is_ident_start(bytes[i]) {
let start = i;
i += 1;
while i < bytes.len() && is_ident_cont(bytes[i]) {
i += 1;
}
let ident_end = i;
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i < bytes.len() && bytes[i] == b'(' {
i += 1;
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i < bytes.len() && (bytes[i] == b'\'' || bytes[i] == b'"') {
let q = bytes[i];
i += 1;
let path_start = i;
while i < bytes.len() && bytes[i] != q {
i += 1;
}
if i < bytes.len() && bytes[i] == q {
let path = s[path_start..i].to_string();
i += 1;
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i < bytes.len() && bytes[i] == b')' {
i += 1;
let display = s[start..i].to_string();
return Some((i, display, path));
}
}
}
}
i = ident_end.max(start + 1);
continue;
}
i += 1;
}
None
}
fn is_ident_start(b: u8) -> bool {
b.is_ascii_alphabetic() || b == b'_'
}
fn is_ident_cont(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
fn collect_quoted_and_words(s: &str, out: &mut Vec<(String, String)>) {
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i].is_ascii_whitespace() {
i += 1;
continue;
}
if bytes[i] == b'\'' || bytes[i] == b'"' {
let q = bytes[i];
i += 1;
let start = i;
while i < bytes.len() && bytes[i] != q {
i += 1;
}
let inner = &s[start..i];
if i < bytes.len() {
i += 1;
}
collect_function_calls(inner, out);
collect_quoted_and_words(inner, out);
out.push((inner.to_string(), inner.to_string()));
continue;
}
let start = i;
while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
i += 1;
}
let raw = &s[start..i];
let peeled = peel_shell_meta(raw);
out.push((raw.to_string(), peeled.to_string()));
if let Some((_, after)) = peeled.rsplit_once(':') {
out.push((raw.to_string(), after.to_string()));
}
}
}
pub fn default_secret_denies() -> Vec<String> {
vec![
"**/.env".into(),
"**/.env.*".into(),
"**/*.pem".into(),
"**/*.key".into(),
"**/*.p12".into(),
"**/*.pfx".into(),
"**/id_rsa".into(),
"**/id_ed25519".into(),
"**/id_ecdsa".into(),
"**/id_dsa".into(),
"**/id_eddsa".into(),
"**/.npmrc".into(),
"**/.pypirc".into(),
"**/.docker/config.json".into(),
"**/kubeconfig".into(),
"**/.kube/config".into(),
"**/secrets.json".into(),
"**/service-account*.json".into(),
"**/.ssh/**".into(),
"**/token.json".into(),
"**/secring.gpg".into(),
"**/.gnupg/private-keys-v1.d/**".into(),
"**/credentials.json".into(),
"**/.aws/credentials".into(),
"**/.netrc".into(),
"**/secrets/**".into(),
"**/credentials/**".into(),
"**/gateway/pairing.json".into(),
"**/auth.json".into(),
"**/auth-*.json".into(),
]
}
#[cfg(test)]
mod classify_hardlink_tests {
use super::*;
use std::path::Path;
#[test]
fn hardlink_denied_when_canon_is_missing() {
let dir = tempfile::tempdir().expect("tempdir");
let env = dir.path().join(".env");
std::fs::write(&env, "API_KEY=secret\n").expect("write .env");
let sibling = dir.path().join("notes.txt");
std::fs::hard_link(&env, &sibling).expect("hardlink");
let policy = DenyPolicy::default();
assert!(
hardlink_sibling_denied(&sibling, None, &policy),
"nlink > 1 must dest-deny when canonicalize is unavailable"
);
assert!(!hardlink_sibling_denied(
Path::new("no-such-workpen-hardlink-xyz"),
None,
&policy
));
}
#[cfg(unix)]
#[test]
fn hardlink_directory_is_scanned_once_inside_a_collect_scope() {
let dir = tempfile::tempdir().expect("tempdir");
let plain = dir.path().join("plain.txt");
std::fs::write(&plain, b"ok").expect("plain");
for i in 0..24 {
std::fs::hard_link(&plain, dir.path().join(format!("link-{i}"))).expect("link");
}
std::fs::hard_link(&plain, dir.path().join(".env")).expect("secret name");
let policy = DenyPolicy::default();
reset_hardlink_dir_reads();
{
let _scope = HardlinkScanScope::new();
for i in 0..24 {
let path = dir.path().join(format!("link-{i}"));
assert!(
hardlink_sibling_denied(&path, None, &policy),
"link-{i} shares an inode with .env"
);
}
}
let scoped = hardlink_dir_reads();
assert!(
scoped <= 2,
"one collect scans the directory once, got {scoped}"
);
let outside = tempfile::tempdir().expect("outside root");
let canon_dir = std::fs::canonicalize(dir.path()).expect("canon dir");
let slash = path_as_glob(&canon_dir.join(".env"));
let custom = DenyPolicy::new(vec![slash]);
reset_hardlink_dir_reads();
{
let _scope = HardlinkScanScope::new();
assert!(
classify_dest_hit_root(&plain, &custom, Some(outside.path())).is_none(),
"outside a non-** slash glob the hardlink is not a secret yet"
);
let reads = hardlink_dir_reads();
assert!(
classify_dest_hit_root(&plain, &custom, None).is_some(),
"the same scan must dest-deny plain.txt once the root is unset"
);
assert_eq!(
hardlink_dir_reads(),
reads,
"the second root reuses the directory read"
);
}
reset_hardlink_dir_reads();
for i in 0..24 {
let path = dir.path().join(format!("link-{i}"));
assert!(hardlink_sibling_denied(&path, None, &policy));
}
let unscoped = hardlink_dir_reads();
assert!(
unscoped >= 24,
"without a collect scope each name scans the directory, got {unscoped}"
);
}
#[cfg(unix)]
#[test]
fn multicall_names_in_another_directory_are_not_a_denied_sibling() {
let dir = tempfile::tempdir().expect("tempdir");
let lib = dir.path().join("coreutils");
let bin = dir.path().join("bin");
std::fs::create_dir(&lib).expect("lib");
std::fs::create_dir(&bin).expect("bin");
let echo_lib = lib.join("echo");
std::fs::write(&echo_lib, b"echo").expect("echo");
std::fs::hard_link(&echo_lib, lib.join("sleep")).expect("sleep");
std::fs::hard_link(&echo_lib, lib.join("printenv")).expect("printenv");
let echo_bin = bin.join("echo");
std::fs::hard_link(&echo_lib, &echo_bin).expect("bin echo");
let policy = DenyPolicy::default();
assert_eq!(
classify_dest(&echo_bin, &policy),
Some(DestDenyKind::HardlinkSibling),
"unseen multicall names must still fail closed"
);
TEST_LINK_DIRS.with(|dirs| dirs.borrow_mut().push(lib.clone()));
struct ClearHook;
impl Drop for ClearHook {
fn drop(&mut self) {
TEST_LINK_DIRS.with(|dirs| dirs.borrow_mut().clear());
}
}
let _clear = ClearHook;
assert_eq!(
classify_dest(&echo_bin, &policy),
None,
"scanning the other multicall directory must allow echo"
);
std::fs::hard_link(&echo_lib, lib.join(".env")).expect("secret name");
assert_eq!(
classify_dest(&echo_bin, &policy),
Some(DestDenyKind::HardlinkSibling),
"a .env name on the multicall inode must stay denied"
);
}
#[cfg(unix)]
#[test]
fn program_link_dirs_include_cargo_coreutils() {
let dirs = extra_link_dirs();
assert!(
dirs.iter()
.any(|dir| dir == Path::new("/usr/lib/cargo/bin/coreutils")),
"ubuntu multicall dir missing from the hardlink scan"
);
}
#[test]
fn win_find_next_exhausted_is_eof_not_other_errors() {
assert!(win_find_next_exhausted(WIN_ERROR_NO_MORE_FILES));
assert!(win_find_next_exhausted(WIN_ERROR_HANDLE_EOF));
assert!(!win_find_next_exhausted(5));
assert!(!win_find_next_exhausted(234));
}
#[test]
fn win_names_shorter_than_nlink_is_hardlink_sibling() {
let policy = DenyPolicy::default();
let names = [std::ffi::OsString::from(r"C:\ws\notes.txt")];
match hardlink_hit_from_win_names(&names, 2, &policy, None) {
HardlinkHit::Denied { sibling: None } => {}
other => panic!("incomplete name list must deny, got {other:?}"),
}
}
#[test]
fn win_names_matching_nlink_without_deny_glob_is_allowed() {
let policy = DenyPolicy::default();
let names = [std::ffi::OsString::from(r"C:\ws\notes.txt")];
match hardlink_hit_from_win_names(&names, 1, &policy, None) {
HardlinkHit::Allowed => {}
other => panic!("single name and nlink 1 must allow, got {other:?}"),
}
let two = [
std::ffi::OsString::from(r"C:\ws\a.txt"),
std::ffi::OsString::from(r"C:\ws\b.txt"),
];
match hardlink_hit_from_win_names(&two, 2, &policy, None) {
HardlinkHit::Allowed => {}
other => panic!("listed names with no deny glob must allow, got {other:?}"),
}
}
#[test]
fn win_names_denied_glob_reports_sibling_basename() {
let policy = DenyPolicy::default();
let names = [
std::ffi::OsString::from(r"C:\ws\.env"),
std::ffi::OsString::from(r"C:\ws\notes.txt"),
];
match hardlink_hit_from_win_names(&names, 2, &policy, None) {
HardlinkHit::Denied {
sibling: Some(name),
} => assert_eq!(name, ".env"),
other => panic!("hardlink of .env must name sibling, got {other:?}"),
}
}
#[test]
fn win_names_prefer_earlier_deny_glob_over_list_order() {
let policy = DenyPolicy::default();
let names = [
std::ffi::OsString::from(r"C:\ws\.env.example-link"),
std::ffi::OsString::from(r"C:\ws\notes.txt"),
std::ffi::OsString::from(r"C:\ws\.env"),
];
match hardlink_hit_from_win_names(&names, 3, &policy, None) {
HardlinkHit::Denied {
sibling: Some(name),
} => assert_eq!(name, ".env"),
other => panic!("earlier deny glob must win, got {other:?}"),
}
}
}