use std::sync::{Arc, OnceLock};
use crate::error::Result;
use regex::Regex;
use serde_derive::{Deserialize, Serialize};
use tracing::{debug, warn};
use crate::{
blast_radius::{self, BlastRadiusInfo, BlastScope},
config::{Challenge, ResolvedSettings, Settings},
context::{self, RuntimeContext},
env::Environment,
policy::{self, MergedPolicy},
prompt::{AlternativeInfo, ChallengeResult, DisplayContext, Prompter},
};
pub const SENSITIVE_PATH_MARKER: &str = "shellfirm-sensitive-path";
pub const PROTECTED_FORCE_PUSH_MARKER: &str = "shellfirm-force-push-protected";
pub const UNKNOWN_TARGET_FORCE_PUSH_MARKER: &str = "shellfirm-force-push-unknown-target";
pub const REPOSITORY_DELETE_MARKER: &str = "shellfirm-delete-repository";
pub const WORK_MOVED_AWAY_MARKER: &str = "shellfirm-move-work-away";
pub const GIT_DIR_DELETE_MARKER: &str = "shellfirm-delete-git-dir";
pub const LINE_CONTEXT_MARKER: &str = "shellfirm-line-context";
pub const PRIVILEGED_MARKER: &str = "shellfirm-privileged";
const PRIVILEGE_SURVIVORS: &[&str] = &[
"fs:lvm_operations",
"fs:encryption_operations",
"fs:rsync_delete",
"shell:curl_pipe_to_interpreter",
"kubernetes:velero_restore",
"fs:recursively_delete_outside",
"fs:flush_file_content",
"fs:recursively_chmod",
"fs:recursively_chown",
"fs:truncate_zero",
];
const MAX_REPOSITORY_LOOKUPS: usize = 4096;
fn deleted_repositories(env: &dyn Environment, parsed: &crate::parser::Parsed) -> Vec<String> {
let home = env.home_dir();
let cwd = env.current_dir().ok();
let mut out = Vec::new();
let mut looked_up = std::collections::HashSet::new();
for seg in &parsed.segments {
if !seg.starts_with("rm ") || parsed.remote_segments.binary_search(seg).is_ok() {
continue;
}
if looked_up.len() > MAX_REPOSITORY_LOOKUPS {
break;
}
let words: Vec<String> = seg.split(' ').map(crate::parser::desentinel).collect();
let recursive = words.iter().skip(1).any(|w| {
w == "--recursive"
|| (w.starts_with('-') && !w.starts_with("--") && w.contains(['r', 'R']))
});
if !recursive {
continue;
}
for op in words
.iter()
.skip(1)
.take_while(|w| !crate::parser::is_redirect_word(w))
.filter(|w| !w.starts_with('-') && !w.contains('$'))
{
if !looked_up.insert(op.clone()) {
continue;
}
if op.contains(['*', '?', '[']) {
let (dir, pattern) = op.rsplit_once('/').unwrap_or((".", op.as_str()));
if dir.contains(['*', '?', '[']) || !glob_matches(pattern, ".git") {
continue;
}
let base = match (dir.strip_prefix('~'), &home) {
(Some(rest), Some(h)) => h.join(rest.trim_start_matches('/')),
_ => cwd
.as_ref()
.map_or_else(|| std::path::PathBuf::from(dir), |c| c.join(dir)),
};
if env.read_file(&base.join(".git").join("HEAD")).is_ok() && !out.contains(op) {
out.push(op.clone());
}
continue;
}
if matches!(op.as_str(), "." | ".." | "~" | "/" | ".git") {
continue;
}
let path = match (op.strip_prefix("~/"), &home) {
(Some(rest), Some(h)) => h.join(rest),
_ if op.starts_with('~') && expand_user_tilde(op).is_some() => {
std::path::PathBuf::from(expand_user_tilde(op).unwrap_or_default())
}
_ => cwd
.as_ref()
.map_or_else(|| std::path::PathBuf::from(op), |c| c.join(op)),
};
if op.ends_with("/.git") {
let marked = format!("{GIT_DIR_DELETE_MARKER} {op}");
if env.read_file(&path.join("HEAD")).is_ok() && !out.contains(&marked) {
out.push(marked);
}
continue;
}
let is_repo = env.read_file(&path.join(".git").join("HEAD")).is_ok()
|| env
.read_file(&path.join(".git"))
.is_ok_and(|c| c.trim_start().starts_with("gitdir:"));
if is_repo && !out.contains(op) {
out.push(op.clone());
}
}
}
out
}
fn repositories_moved_away(env: &dyn Environment, parsed: &crate::parser::Parsed) -> Vec<String> {
const SCRATCH: &[&str] = &["/tmp", "/var/tmp", "/dev/shm", "/private/tmp", "/dev/null"];
let home = env.home_dir();
let cwd = env.current_dir().ok();
let mut out = Vec::new();
for seg in &parsed.segments {
if !seg.starts_with("mv ") || parsed.remote_segments.binary_search(seg).is_ok() {
continue;
}
let words: Vec<String> = seg.split(' ').map(crate::parser::desentinel).collect();
let ops: Vec<&String> = words[1..]
.iter()
.take_while(|w| !crate::parser::is_redirect_word(w))
.filter(|w| !w.starts_with('-'))
.collect();
let Some((dest, sources)) = ops.split_last() else {
continue;
};
let dest = crate::parser::normalize_path(dest);
if sources.is_empty()
|| !SCRATCH
.iter()
.any(|t| dest == *t || dest.starts_with(&format!("{t}/")))
{
continue;
}
for src in sources.iter().filter(|w| !w.contains(['$', '*', '?', '['])) {
let path = match (src.strip_prefix("~/"), &home) {
(Some(rest), Some(h)) => h.join(rest),
_ => cwd.as_ref().map_or_else(
|| std::path::PathBuf::from(src.as_str()),
|c| c.join(src.as_str()),
),
};
let is_repo = env.read_file(&path.join(".git").join("HEAD")).is_ok()
|| env
.read_file(&path.join(".git"))
.is_ok_and(|c| c.trim_start().starts_with("gitdir:"));
if is_repo && !out.contains(*src) {
out.push((*src).clone());
}
}
}
out
}
fn empty_variable_segments(env: &dyn Environment, parsed: &crate::parser::Parsed) -> Vec<String> {
let mut out = Vec::new();
for seg in &parsed.segments {
if !seg.starts_with("rm ")
|| !seg.contains('$')
|| parsed.remote_segments.binary_search(seg).is_ok()
{
continue;
}
let words: Vec<&str> = seg.split(' ').collect();
let recursive = words.iter().skip(1).any(|w| {
*w == "--recursive"
|| (w.starts_with('-') && !w.starts_with("--") && w.contains(['r', 'R']))
});
if !recursive {
continue;
}
let mut changed = false;
let new_words: Vec<String> = words
.iter()
.enumerate()
.map(|(i, w)| {
if i == 0 || w.starts_with('-') {
return (*w).to_string();
}
let t = w.trim_end_matches('/');
let Some((prefix, last)) = t.rsplit_once('/') else {
return (*w).to_string();
};
let name = last
.strip_prefix("${")
.and_then(|n| n.strip_suffix('}'))
.or_else(|| last.strip_prefix('$'))
.filter(|n| {
!n.is_empty() && n.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
});
match name {
Some(n)
if prefix.is_empty()
|| !prefix.contains('$')
|| prefix == "$HOME"
|| prefix == "${HOME}" =>
{
if env.var(n).is_some_and(|v| !v.is_empty()) {
return (*w).to_string();
}
changed = true;
if matches!(prefix, "~" | "$HOME" | "${HOME}") {
prefix.to_string()
} else {
format!("{prefix}/")
}
}
_ => (*w).to_string(),
}
})
.collect();
if changed {
out.push(new_words.join(" "));
}
}
out
}
const REGENERABLE_DIRS: &[&str] = &[
"node_modules",
"build",
"dist",
"target",
"out",
".next",
".nuxt",
".turbo",
".parcel-cache",
".cache",
"coverage",
"__pycache__",
".pytest_cache",
".mypy_cache",
".ruff_cache",
".tox",
".venv",
"venv",
".gradle",
"bin",
"obj",
"tmp",
];
const UNCOMMITTED_WORK_TIMEOUT_MS: u64 = 200;
const UNCOMMITTED_WORK_MIN_MS: u64 = 50;
const MAX_UNCOMMITTED_WORK_PATHS: usize = 32;
const SCRATCH_DIRS: &[&str] = &["/tmp", "/var/tmp", "/dev/shm", "/private/tmp", "/dev/null"];
fn deleted_folder_operands(seg: &str) -> Vec<String> {
let words: Vec<String> = seg.split(' ').map(crate::parser::desentinel).collect();
let Some(prog) = words.first() else {
return Vec::new();
};
let args: Vec<&String> = words[1..]
.iter()
.take_while(|w| !crate::parser::is_redirect_word(w))
.collect();
let ops: Vec<String> = match prog.as_str() {
"rm" => {
let recursive = args.iter().any(|w| {
*w == "--recursive"
|| (w.starts_with('-') && !w.starts_with("--") && w.contains(['r', 'R']))
});
if !recursive {
return Vec::new();
}
args.iter()
.filter(|w| !w.starts_with('-'))
.map(|w| (*w).clone())
.collect()
}
"find" => {
let start = args
.iter()
.position(|w| w.starts_with(['-', '(', '!']))
.unwrap_or(args.len());
let expr = &args[start..];
let whole_tree = expr.iter().any(|w| *w == "-delete")
&& expr.iter().all(|w| {
matches!(
w.as_str(),
"-delete" | "-depth" | "-xdev" | "-mount" | "-mindepth" | "-maxdepth"
) || w.chars().all(|c| c.is_ascii_digit())
});
if !whole_tree {
return Vec::new();
}
args[..start].iter().map(|w| (*w).clone()).collect()
}
"mv" => {
let ops: Vec<&String> = args
.iter()
.copied()
.filter(|w| !w.starts_with('-'))
.collect();
let Some((dest, sources)) = ops.split_last() else {
return Vec::new();
};
let dest = crate::parser::normalize_path(dest);
if !SCRATCH_DIRS
.iter()
.any(|t| dest == *t || dest.starts_with(&format!("{t}/")))
{
return Vec::new();
}
sources.iter().map(|w| (*w).clone()).collect()
}
_ => Vec::new(),
};
ops.into_iter()
.map(|op| {
let mut op = op.as_str();
for suffix in ["/*", "/.*", "/."] {
if let Some(rest) = op.strip_suffix(suffix) {
op = if rest.is_empty() { "/" } else { rest };
break;
}
}
op.to_string()
})
.filter(|op| !op.is_empty() && !op.contains(['$', '*', '?', '[', '{', '`']))
.collect()
}
#[derive(Debug, Default, PartialEq, Eq)]
struct WorkFolders {
dirty: Vec<String>,
unknown: Vec<String>,
}
#[allow(clippy::too_many_lines)]
fn folders_with_uncommitted_work(
env: &dyn Environment,
parsed: &crate::parser::Parsed,
) -> WorkFolders {
let home = env.home_dir();
let Ok(cwd) = env.current_dir() else {
return WorkFolders::default();
};
let mut repo: Option<std::path::PathBuf> = None;
let mut candidates: Vec<(String, String)> = Vec::new();
for seg in &parsed.segments {
if parsed.remote_segments.binary_search(seg).is_ok() {
continue;
}
for op in deleted_folder_operands(seg) {
if candidates.len() >= MAX_UNCOMMITTED_WORK_PATHS {
break;
}
let path = match (op.strip_prefix('~'), &home) {
(Some(rest), Some(h)) if rest.is_empty() || rest.starts_with('/') => {
h.join(rest.trim_start_matches('/'))
}
_ => cwd.join(&op),
};
let path = std::path::PathBuf::from(crate::parser::normalize_path(
&path.display().to_string(),
));
let name = path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
if name.is_empty() || name == ".git" || REGENERABLE_DIRS.contains(&name.as_str()) {
continue;
}
if !std::fs::metadata(&path).is_ok_and(|m| m.is_dir()) {
continue;
}
let Some(parent) = path.parent() else {
continue;
};
let dir_repo = env
.find_file_upward(parent, ".git/HEAD")
.and_then(|h| h.parent()?.parent().map(std::path::Path::to_path_buf));
let file_repo = env
.find_file_upward(parent, ".git")
.and_then(|g| g.parent().map(std::path::Path::to_path_buf));
let Some(root) = [dir_repo, file_repo]
.into_iter()
.flatten()
.max_by_key(|r| r.components().count())
else {
continue;
};
if path.join(".git").exists() {
continue;
}
match &repo {
None => repo = Some(root.clone()),
Some(r) if *r != root => continue,
Some(_) => {}
}
if let Ok(rel) = path.strip_prefix(&root) {
let rel = rel.display().to_string();
if !rel.is_empty() && !candidates.iter().any(|(o, _)| *o == op) {
candidates.push((op.clone(), rel));
}
}
}
}
let Some(root) = repo else {
return WorkFolders::default();
};
if candidates.is_empty() {
return WorkFolders::default();
}
let root_s = root.display().to_string();
let mut args: Vec<&str> = vec![
"-C",
&root_s,
"status",
"--porcelain",
"--untracked-files=normal",
"--",
];
let fixed = args.len();
for (_, r) in &candidates {
if !args[fixed..].contains(&r.as_str()) {
args.push(r);
}
}
let status = env.run_command_outcome("git", &args, uncommitted_work_timeout_ms());
debug!("uncommitted work: git {args:?} -> {status:?}");
let status = match status {
crate::env::CommandOutcome::Output(o) => o,
crate::env::CommandOutcome::TimedOut => {
return WorkFolders {
dirty: Vec::new(),
unknown: candidates.into_iter().map(|(op, _)| op).collect(),
};
}
crate::env::CommandOutcome::Failed | crate::env::CommandOutcome::Skipped => {
return WorkFolders::default();
}
};
let changed: Vec<String> = status
.lines()
.filter_map(|l| l.trim_start().split_once(' ').map(|(_, p)| p))
.flat_map(|p| p.split(" -> "))
.map(|p| unquote_git_path(p.trim()).trim_end_matches('/').to_string())
.collect();
WorkFolders {
dirty: candidates
.into_iter()
.filter(|(_, rel)| {
changed.iter().any(|p| {
p == rel
|| p.starts_with(&format!("{rel}/"))
|| rel.starts_with(&format!("{p}/"))
})
})
.map(|(op, _)| op)
.collect(),
unknown: Vec::new(),
}
}
fn unquote_git_path(p: &str) -> String {
let Some(inner) = p.strip_prefix('"').and_then(|s| s.strip_suffix('"')) else {
return p.to_string();
};
let bytes = inner.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] != b'\\' || i + 1 == bytes.len() {
out.push(bytes[i]);
i += 1;
continue;
}
let next = bytes[i + 1];
let octal = bytes
.get(i + 1..i + 4)
.filter(|d| d.iter().all(|b| (b'0'..=b'7').contains(b)));
if let Some(d) = octal {
let v = d.iter().fold(0u32, |acc, b| acc * 8 + u32::from(b - b'0'));
out.push(u8::try_from(v).unwrap_or(b'?'));
i += 4;
continue;
}
out.push(match next {
b'n' => b'\n',
b't' => b'\t',
b'r' => b'\r',
b'a' => 0x07,
b'b' => 0x08,
b'f' => 0x0c,
b'v' => 0x0b,
other => other,
});
i += 2;
}
String::from_utf8_lossy(&out).into_owned()
}
fn uncommitted_work_timeout_ms() -> u64 {
let budget =
crate::env::scope_budget_ms().unwrap_or(crate::config::DEFAULT_BLAST_RADIUS_BUDGET_MS);
let spent = crate::env::scope_start().map_or(0, |s| {
u64::try_from(s.elapsed().as_millis()).unwrap_or(u64::MAX)
});
budget
.saturating_sub(spent)
.clamp(UNCOMMITTED_WORK_MIN_MS, UNCOMMITTED_WORK_TIMEOUT_MS)
}
const UNCOMMITTED_WORK_NOTE: &str =
"The folder has uncommitted or untracked files: git cannot bring them back.";
const UNCOMMITTED_WORK_UNKNOWN_NOTE: &str =
"shellfirm could not check for uncommitted files in time, so it assumes there are some.";
fn raise_for_uncommitted_work(
folders: &WorkFolders,
segments: &[String],
matches: Vec<&Check>,
) -> Vec<Check> {
let candidate = |c: &Check| {
(c.from.starts_with("fs") && c.severity < Severity::High) || c.id == "fs:move_work_away"
};
if folders.dirty.is_empty() && folders.unknown.is_empty()
|| !matches.iter().any(|c| candidate(c))
{
return matches.into_iter().cloned().collect();
}
let hit = |c: &Check, list: &[String]| {
segments.iter().any(|s| {
c.test.is_match(s)
&& s.strip_prefix(WORK_MOVED_AWAY_MARKER).map_or_else(
|| deleted_folder_operands(s).iter().any(|w| list.contains(w)),
|op| list.iter().any(|w| w == op.trim_start()),
)
})
};
matches
.into_iter()
.map(|c| {
let mut c = c.clone();
if candidate(&c) {
let note = if hit(&c, &folders.dirty) {
Some(UNCOMMITTED_WORK_NOTE)
} else if hit(&c, &folders.unknown) {
Some(UNCOMMITTED_WORK_UNKNOWN_NOTE)
} else {
None
};
if let Some(note) = note {
c.severity = Severity::High;
c.description = format!("{} {note}", c.description.trim_end());
}
}
c
})
.collect()
}
fn restored_paths(seg: &str) -> Option<Vec<String>> {
let words: Vec<String> = seg.split(' ').map(crate::parser::desentinel).collect();
let (sub, rest) = match words.as_slice() {
[git, sub, rest @ ..] if git == "git" => (sub.as_str(), rest),
_ => return None,
};
let rest: Vec<&String> = rest
.iter()
.take_while(|w| !crate::parser::is_redirect_word(w))
.collect();
let paths: Vec<String> = match sub {
"restore" => {
if rest.iter().any(|w| {
w.starts_with("--source")
|| (w.starts_with('-') && !w.starts_with("--") && w.contains('s'))
}) {
return None;
}
rest.iter()
.filter(|w| !w.starts_with('-'))
.map(|w| (*w).clone())
.collect()
}
"checkout" => {
let dd = rest.iter().position(|w| *w == "--")?;
if rest[..dd].iter().any(|w| !w.starts_with('-')) {
return None;
}
rest[dd + 1..].iter().map(|w| (*w).clone()).collect()
}
_ => return None,
};
let plain = |p: &String| {
!p.is_empty()
&& !p.starts_with(':')
&& !p.contains(['$', '*', '?', '[', '{', '`'])
&& p != "."
};
(!paths.is_empty() && paths.iter().all(plain)).then_some(paths)
}
fn drop_restores_of_clean_paths(
env: &dyn Environment,
segments: &[String],
remote: &[String],
matches: Vec<Check>,
) -> Vec<Check> {
const IDS: &[&str] = &["git:restore_discard_path", "git:checkout_discard_path"];
if !matches.iter().any(|c| IDS.contains(&c.id.as_str())) {
return matches;
}
let clean = |c: &Check| {
let segs: Vec<&String> = segments
.iter()
.filter(|s| c.test.is_match(s) && remote.binary_search(s).is_err())
.collect();
!segs.is_empty()
&& segs.iter().all(|s| {
let Some(paths) = restored_paths(s) else {
return false;
};
let mut args = vec!["status", "--porcelain", "--untracked-files=no", "--"];
args.extend(paths.iter().map(String::as_str));
matches!(
env.run_command_outcome("git", &args, uncommitted_work_timeout_ms()),
crate::env::CommandOutcome::Output(ref o) if o.trim().is_empty()
)
})
};
matches
.into_iter()
.filter(|c| !(IDS.contains(&c.id.as_str()) && clean(c)))
.collect()
}
fn glob_matches(pattern: &str, name: &str) -> bool {
fn go(p: &[char], n: &[char]) -> bool {
match p.split_first() {
None => n.is_empty(),
Some(('*', rest)) => (0..=n.len()).any(|k| go(rest, &n[k..])),
Some(('?', rest)) => !n.is_empty() && go(rest, &n[1..]),
Some(('[', rest)) => {
let Some(close) = rest.iter().skip(1).position(|c| *c == ']').map(|p| p + 1) else {
return n.first() == Some(&'[') && go(rest, &n[1..]);
};
let Some(&c) = n.first() else { return false };
let class = &rest[..close];
let (negate, class) = match class.split_first() {
Some(('!' | '^', r)) => (true, r),
_ => (false, class),
};
let mut hit = false;
let mut i = 0;
while i < class.len() {
if i + 2 < class.len() && class[i + 1] == '-' {
hit |= class[i] <= c && c <= class[i + 2];
i += 3;
} else {
hit |= class[i] == c;
i += 1;
}
}
hit != negate && go(&rest[close + 1..], &n[1..])
}
Some((c, rest)) => n.first() == Some(c) && go(rest, &n[1..]),
}
}
let p: Vec<char> = pattern.chars().collect();
let n: Vec<char> = name.chars().collect();
if n.first() == Some(&'.') && p.first() != Some(&'.') {
return false;
}
go(&p, &n)
}
const HOME_CREDENTIAL_DIRS: &[&str] = &[
".ssh",
".gnupg",
".aws",
".kube",
".azure",
".docker",
".password-store",
".config/gcloud",
];
const RESOLVED_PROGRAMS: &[&str] = &[
"rm", "rmdir", "unlink", "shred", "srm", "mv", "chmod", "chown", "chgrp", "find", "cp", "ln",
"tee", "truncate",
];
fn is_user_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 32
&& name
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
}
#[cfg(unix)]
pub(crate) fn user_home(name: &str) -> Option<String> {
if !is_user_name(name) {
return None;
}
let c_name = std::ffi::CString::new(name).ok()?;
let mut buf = vec![0 as libc::c_char; 16 * 1024];
let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
let mut result: *mut libc::passwd = std::ptr::null_mut();
let rc = unsafe {
libc::getpwnam_r(
c_name.as_ptr(),
&raw mut pwd,
buf.as_mut_ptr(),
buf.len(),
&raw mut result,
)
};
if rc != 0 || result.is_null() || pwd.pw_dir.is_null() {
return None;
}
let dir = unsafe { std::ffi::CStr::from_ptr(pwd.pw_dir) }
.to_string_lossy()
.to_string();
(dir.starts_with('/')).then_some(dir)
}
#[cfg(not(unix))]
pub(crate) const fn user_home(_name: &str) -> Option<String> {
None
}
pub(crate) fn expand_user_tilde(word: &str) -> Option<String> {
let rest = word.strip_prefix('~')?;
let (name, tail) = rest.split_once('/').unwrap_or((rest, ""));
if name.is_empty() {
return None;
}
let home = user_home(name)?;
Some(crate::parser::normalize_path(&if tail.is_empty() {
home
} else {
format!("{home}/{tail}")
}))
}
const FOLLOW_LAST_LINK_PROGRAMS: &[&str] = &["chmod", "chown", "chgrp", "truncate", "shred"];
const MAX_SYMLINK_RESOLUTIONS: usize = 64;
fn real_location(env: &dyn Environment, abs: &str, follow_last: bool) -> Option<String> {
let path = std::path::Path::new(abs);
let parent = path.parent()?;
if !env.path_exists(parent) {
return None;
}
let real = if follow_last && env.path_exists(path) {
std::fs::canonicalize(path).ok()?
} else {
let name = path.file_name()?;
std::fs::canonicalize(parent).ok()?.join(name)
};
let real = crate::parser::normalize_path(&real.display().to_string());
(real != abs && real.strip_prefix("/private") != Some(abs)).then_some(real)
}
fn written_with_trailing_slash(command: &str, operand: &str) -> bool {
let last = operand.rsplit('/').next().unwrap_or(operand);
if last.is_empty() || matches!(last, "." | ".." | "~") {
return false;
}
let needle = format!("{last}/");
command.match_indices(&needle).any(|(i, _)| {
command[i + needle.len()..].chars().next().is_none_or(|c| {
c.is_whitespace() || matches!(c, '\'' | '"' | '*' | '.' | ';' | '&' | '|' | ')')
})
})
}
#[allow(clippy::too_many_lines)]
fn cwd_resolved_segments(
env: &dyn Environment,
parsed: &crate::parser::Parsed,
command: &str,
) -> Vec<String> {
let Ok(cwd) = env.current_dir() else {
return Vec::new();
};
let cwd = crate::parser::normalize_path(&cwd.display().to_string());
let home = env
.home_dir()
.map(|h| crate::parser::normalize_path(&h.display().to_string()));
let under = |p: &str, base: &str| -> Option<String> {
if p == base {
Some(String::new())
} else if base == "/" {
p.strip_prefix('/').map(str::to_string)
} else {
p.strip_prefix(base)
.and_then(|r| r.strip_prefix('/'))
.map(str::to_string)
}
};
let absolute = |w: &str| -> Option<String> {
if w.is_empty() || w.starts_with('-') || w.contains('$') || w.contains("{}") {
return None;
}
let p = if let Some(user_path) = expand_user_tilde(w) {
user_path
} else if let Some(rest) = w.strip_prefix('~') {
let h = home.as_deref()?;
if rest.is_empty() {
h.to_string()
} else {
format!("{h}/{}", rest.strip_prefix('/')?)
}
} else if w.starts_with('/') {
w.to_string()
} else {
format!("{cwd}/{w}")
};
Some(crate::parser::normalize_path(&p))
};
let home_form = |abs: &str| -> String {
match home.as_deref().and_then(|h| under(abs, h)) {
Some(r) if r.is_empty() => "~".to_string(),
Some(r) => format!("~/{r}"),
None => abs.to_string(),
}
};
let interesting_home_form = |h: &str| -> bool {
h.strip_prefix("~/").map_or_else(
|| {
h == "~"
|| (h.starts_with('/')
&& !["/tmp", "/var/tmp", "/private/tmp"]
.iter()
.any(|t| h == *t || h.starts_with(&format!("{t}/"))))
},
|r| {
!r.contains('/')
|| r == "*"
|| HOME_CREDENTIAL_DIRS
.iter()
.any(|d| r == *d || r.starts_with(&format!("{d}/")))
},
)
};
let home_real = home
.as_deref()
.and_then(|h| std::fs::canonicalize(h).ok())
.map(|h| crate::parser::normalize_path(&h.display().to_string()));
let real_home_form = |real: &str| -> String {
match home_real.as_deref().and_then(|h| under(real, h)) {
Some(r) if r.is_empty() => "~".to_string(),
Some(r) => format!("~/{r}"),
None => home_form(real),
}
};
let mut resolutions = 0usize;
let mut out = Vec::new();
for seg in &parsed.segments {
if parsed.remote_segments.binary_search(seg).is_ok() {
continue;
}
let words: Vec<&str> = seg.split(' ').collect();
let Some(prog) = words.first().copied() else {
continue;
};
let path_prog = RESOLVED_PROGRAMS.contains(&prog);
if !path_prog && !seg.contains('>') {
continue;
}
let mut as_home = words.iter().map(|w| (*w).to_string()).collect::<Vec<_>>();
let mut as_cwd = as_home.clone();
let (mut home_changed, mut cwd_changed) = (false, false);
let mut seen_operand = false;
let mut i = usize::from(!crate::parser::is_redirect_word(prog));
while i < words.len() {
let w = words[i];
let target = if crate::parser::is_redirect_word(w) {
if !w.contains('>') || w.ends_with('&') {
i += 2;
continue;
}
i += 1;
i
} else if !path_prog || w.starts_with('-') {
if prog == "find" && w.starts_with('-') {
break;
}
i += 1;
continue;
} else {
let skip = matches!(prog, "chmod" | "chown" | "chgrp") && !seen_operand;
seen_operand = true;
if skip {
i += 1;
continue;
}
i
};
let Some(word) = words.get(target) else { break };
let text = crate::parser::desentinel(word);
if let Some(abs) = absolute(&text) {
let user_tilde = text.starts_with('~')
&& !text.starts_with("~/")
&& text != "~"
&& expand_user_tilde(&text).is_some();
let relative = user_tilde || !(text.starts_with('/') || text.starts_with('~'));
let glob_at = abs.find(['*', '?', '[']);
let real = if path_prog && resolutions < MAX_SYMLINK_RESOLUTIONS {
resolutions += 1;
glob_at.map_or_else(
|| {
let follow_last = FOLLOW_LAST_LINK_PROGRAMS.contains(&prog)
|| written_with_trailing_slash(command, &text);
real_location(env, &abs, follow_last)
},
|g| {
abs[..g].rfind('/').and_then(|slash| {
let (dir, tail) = abs.split_at(slash);
let dir = if dir.is_empty() { "/" } else { dir };
real_location(env, dir, true).map(|r| {
if r == "/" {
tail.to_string()
} else {
format!("{r}{tail}")
}
})
})
},
)
} else {
None
};
if let Some(h) = real
.as_deref()
.map(real_home_form)
.filter(|h| *h != home_form(&abs) && interesting_home_form(h))
{
as_home[target] = h.replace(' ', &crate::parser::WS_SENTINEL.to_string());
home_changed = true;
} else if relative {
let h = home_form(&abs);
if interesting_home_form(&h) && h != text {
as_home[target] = h.replace(' ', &crate::parser::WS_SENTINEL.to_string());
home_changed = true;
}
} else if let Some(r) = under(&abs, &cwd) {
let r = if r.is_empty() { ".".to_string() } else { r };
if r == "." || r == "*" || r == ".git" || r.starts_with(".git/") {
as_cwd[target] = r;
cwd_changed = true;
}
}
}
i = target + 1;
}
if home_changed {
out.push(as_home.join(" "));
}
if cwd_changed {
out.push(as_cwd.join(" "));
}
}
let existing: std::collections::HashSet<&String> = parsed.segments.iter().collect();
let mut seen = std::collections::HashSet::new();
out.retain(|s| !existing.contains(s) && seen.insert(s.clone()));
out
}
#[allow(clippy::too_many_lines)]
fn created_path_segments(env: &dyn Environment, parsed: &crate::parser::Parsed) -> Vec<String> {
let Ok(cwd) = env.current_dir() else {
return Vec::new();
};
let cwd = crate::parser::normalize_path(&cwd.display().to_string());
let home = env
.home_dir()
.map(|h| crate::parser::normalize_path(&h.display().to_string()));
let absolute = |w: &str| -> Option<String> {
if w.is_empty() || w.starts_with('-') || w.contains(['$', '*', '?', '[']) || w == "{}" {
return None;
}
let p = if let Some(rest) = w.strip_prefix('~') {
if rest.is_empty() || rest.starts_with('/') {
format!("{}{rest}", home.as_deref()?)
} else {
expand_user_tilde(w)?
}
} else if w.starts_with('/') {
w.to_string()
} else {
format!("{cwd}/{w}")
};
Some(crate::parser::normalize_path(&p))
};
let mut created: Vec<(String, Option<String>)> = Vec::new();
let mut links: Vec<(String, String)> = Vec::new();
let mut fresh_dirs: Vec<(String, bool)> = Vec::new();
let mut out = Vec::new();
let spelled = |abs: &str| -> String {
match home.as_deref() {
Some(h) if abs == h => "~".to_string(),
Some(h) => abs
.strip_prefix(&format!("{h}/"))
.map_or_else(|| abs.to_string(), |r| format!("~/{r}")),
None => abs.to_string(),
}
};
let is_link =
|abs: &str| std::fs::symlink_metadata(abs).is_ok_and(|m| m.file_type().is_symlink());
for seg in &parsed.segments {
if parsed.remote_segments.binary_search(seg).is_ok() {
continue;
}
let words: Vec<String> = seg.split(' ').map(crate::parser::desentinel).collect();
let Some(prog) = words.first().map(String::as_str) else {
continue;
};
let operands: Vec<&String> = words[1..]
.iter()
.take_while(|w| !crate::parser::is_redirect_word(w))
.filter(|w| !w.starts_with('-'))
.collect();
match prog {
"cd" | "pushd" => {
for d in &mut fresh_dirs {
d.1 = true;
}
}
"rm" | "rmdir" | "unlink" | "shred" | "chmod" | "chown" | "chgrp"
if !created.is_empty() || !links.is_empty() || !fresh_dirs.is_empty() =>
{
let skip_first = matches!(prog, "chmod" | "chown" | "chgrp");
let mut new_words = words.clone();
let mut changed = false;
let mut seen = 0usize;
for (i, w) in words.iter().enumerate().skip(1) {
if crate::parser::is_redirect_word(w) {
break;
}
if w.starts_with('-') {
continue;
}
seen += 1;
if skip_first && seen == 1 {
continue;
}
if let Some(glob_at) = w.find(['*', '?', '[']) {
let dir_end = w[..glob_at].rfind('/');
let target = dir_end.and_then(|e| {
let dir = absolute(&w[..e])?;
links
.iter()
.rev()
.find(|(l, _)| *l == dir)
.map(|(_, t)| (t, e))
});
if let Some((t, e)) = target {
let rest = &w[e + 1..];
new_words[i] = if t.ends_with('/') {
format!("{t}{rest}")
} else {
format!("{t}/{rest}")
};
changed = true;
}
continue;
}
let Some(abs) = absolute(w) else { continue };
let made = created
.iter()
.rev()
.find_map(|(c, src)| {
if abs == *c {
Some(src.clone())
} else {
abs.strip_prefix(&format!("{c}/"))
.map(|rest| src.as_ref().map(|s| format!("{s}/{rest}")))
}
})
.or_else(|| {
fresh_dirs
.iter()
.any(|(d, cd)| {
*cd && (abs == *d || abs.starts_with(&format!("{d}/")))
})
.then_some(None)
});
if let Some(made) = made {
if !env.path_exists(std::path::Path::new(&abs)) {
new_words[i] = made.unwrap_or_else(|| "{}".to_string());
changed = true;
}
}
}
if changed {
out.push(
new_words
.iter()
.map(|w| w.replace(' ', &crate::parser::WS_SENTINEL.to_string()))
.collect::<Vec<_>>()
.join(" "),
);
}
}
"ln" | "cp" | "mv" | "rsync" | "install" => {
let target_dir = words
.iter()
.position(|w| w == "-t" || w == "--target-directory")
.and_then(|i| words.get(i + 1))
.or_else(|| {
words
.iter()
.find_map(|w| w.strip_prefix("--target-directory=").map(|_| w))
});
if target_dir.is_none() && operands.len() >= 2 {
if let Some(a) = operands
.last()
.and_then(|w| absolute(w))
.filter(|a| !a.starts_with("/tmp/shellfirm-mktemp."))
{
let sources: Vec<Option<String>> = operands[..operands.len() - 1]
.iter()
.map(|w| absolute(w))
.collect();
let known = sources.iter().all(Option::is_some);
let flags = words[1..]
.iter()
.filter(|w| w.starts_with('-') && !w.starts_with("--"))
.flat_map(|w| w.chars().skip(1))
.collect::<String>();
let long = |f: &str| words.iter().any(|w| w == f);
let entry = match prog {
"mv" if sources.len() == 1
&& known
&& sources.iter().flatten().all(|s| !is_link(s)) =>
{
Some(sources[0].as_deref().map(spelled))
}
"cp" | "rsync" | "install"
if known
&& !flags.contains(['s', 'l'])
&& !long("--symbolic-link")
&& !long("--link")
&& sources.iter().flatten().all(|s| !is_link(s)) =>
{
None
}
_ => Some(None),
};
let symbolic = prog == "ln" && (flags.contains('s') || long("--symbolic"));
if symbolic && sources.len() == 1 {
if let Some(t) = sources[0].as_deref() {
links.push((a.clone(), spelled(t)));
}
}
if let Some(src) = entry {
created.push((a, src));
}
}
}
}
"mkdir" => fresh_dirs.extend(
operands
.iter()
.filter_map(|w| absolute(w))
.filter(|a| {
!["/tmp/", "/var/tmp/", "/private/tmp/"]
.iter()
.any(|t| a.starts_with(t))
})
.map(|a| (a, false)),
),
_ => {}
}
if created.len() + links.len() + fresh_dirs.len() > 256 {
break;
}
}
out
}
fn spell_parent_paths_in_repo(env: &dyn Environment, segments: &mut [String]) {
if !segments
.iter()
.any(|s| s.starts_with("rm ") && s.contains(" ../"))
{
return;
}
let Ok(cwd) = env.current_dir() else {
return;
};
let Some(root) = env
.find_file_upward(&cwd, ".git/HEAD")
.and_then(|h| {
h.parent()
.and_then(std::path::Path::parent)
.map(std::path::Path::to_path_buf)
})
.or_else(|| {
env.find_file_upward(&cwd, ".git")
.and_then(|g| g.parent().map(std::path::Path::to_path_buf))
})
else {
return;
};
let cwd_s = crate::parser::normalize_path(&cwd.display().to_string());
let root_s = crate::parser::normalize_path(&root.display().to_string());
if cwd_s == root_s {
return;
}
for seg in segments.iter_mut().filter(|s| s.starts_with("rm ")) {
let mut words: Vec<String> = seg.split(' ').map(str::to_string).collect();
let mut changed = false;
for w in words.iter_mut().skip(1) {
if !w.starts_with("../") || w.contains(['*', '?', '[', '$', '{']) {
continue;
}
let abs = crate::parser::normalize_path(&format!("{cwd_s}/{w}"));
let inside = abs
.strip_prefix(&root_s)
.and_then(|r| r.strip_prefix('/'))
.is_some_and(|r| !r.is_empty() && r != ".git" && !r.starts_with(".git/"));
if inside {
*w = abs;
changed = true;
}
}
if changed {
*seg = words.join(" ");
}
}
}
const SKIPPED_CACHE_DIRS: &[&str] = &[
"node_modules",
"__pycache__",
".mypy_cache",
".ruff_cache",
".pytest_cache",
".turbo",
".parcel-cache",
".next",
".nuxt",
".svelte-kit",
".angular",
".gradle",
".tox",
".nox",
".dart_tool",
".nyc_output",
".venv",
];
fn quoted_dry_run_words(command: &str, depth: usize, out: &mut Vec<String>) {
let mut word = String::new();
let mut quoted = false;
let mut chars = command.chars().peekable();
let finish = |word: &mut String, quoted: &mut bool, out: &mut Vec<String>| {
if *quoted {
if word.starts_with('-')
&& (word.to_ascii_lowercase().contains("dry")
|| word.starts_with("-o")
|| word.starts_with("--output"))
{
out.push(word.clone());
} else if depth < 4 && word.contains([' ', '\t', '\n', '\'', '"', '\\']) {
quoted_dry_run_words(word, depth + 1, out);
}
}
word.clear();
*quoted = false;
};
while let Some(c) = chars.next() {
match c {
'\'' => {
quoted = true;
for q in chars.by_ref() {
if q == '\'' {
break;
}
word.push(q);
}
}
'"' => {
quoted = true;
while let Some(q) = chars.next() {
match q {
'"' => break,
'\\' if matches!(chars.peek(), Some('"' | '\\' | '$' | '`')) => {
word.push(chars.next().unwrap_or_default());
}
_ => word.push(q),
}
}
}
'\\' => {
quoted = true;
if let Some(n) = chars.next() {
word.push(n);
}
}
'$' if chars.peek() == Some(&'\'') => {}
c if c.is_whitespace() || matches!(c, ';' | '|' | '&' | '(' | ')' | '<' | '>') => {
finish(&mut word, &mut quoted, out);
}
_ => word.push(c),
}
}
finish(&mut word, &mut quoted, out);
}
#[derive(Debug, Default)]
struct RawWord {
text: String,
plain: bool,
single_quoted: Option<String>,
}
#[derive(Debug, Default)]
struct RawCommand {
words: Vec<RawWord>,
end: usize,
stdin: Vec<String>,
piped: bool,
substitutions: Vec<String>,
}
#[allow(clippy::too_many_lines)]
fn nested_len(chars: &[(usize, char)], at: usize, line: &str) -> usize {
#[derive(Clone, Copy, PartialEq, Eq)]
enum In {
Paren,
Brace,
Double,
Tick,
}
let end_of = |i: usize| chars.get(i).map_or(line.len(), |c| c.0);
let mut stack = vec![match chars[at].1 {
'`' => In::Tick,
'{' => In::Brace,
_ => In::Paren,
}];
let mut pending: Vec<String> = Vec::new();
let mut word_start = true;
let mut i = at + 1;
while i < chars.len() {
let Some(&top) = stack.last() else {
break;
};
let c = chars[i].1;
let next = chars.get(i + 1).map(|n| n.1);
match (top, c) {
(_, '\\') => i += 1,
(In::Tick, '`') | (In::Double, '"') | (In::Paren, ')') | (In::Brace, '}') => {
stack.pop();
}
(In::Tick, _) => {}
(_, '$') if matches!(next, Some('(' | '{')) => {
stack.push(if next == Some('(') {
In::Paren
} else {
In::Brace
});
i += 1;
}
(_, '`') => stack.push(In::Tick),
(In::Double, _) => {}
(_, '"') => stack.push(In::Double),
(_, '\'') => {
i += 1;
while i < chars.len() && chars[i].1 != '\'' {
i += 1;
}
}
(In::Paren, '(') => stack.push(In::Paren),
(In::Brace, '{') => stack.push(In::Brace),
(In::Paren, '#') if word_start => {
while i + 1 < chars.len() && chars[i + 1].1 != '\n' {
i += 1;
}
}
(In::Paren, '<')
if next == Some('<') && chars.get(i + 2).is_none_or(|n| n.1 != '<') =>
{
i += 2;
while chars
.get(i)
.is_some_and(|n| matches!(n.1, '-' | ' ' | '\t'))
{
i += 1;
}
let mut delim = String::new();
while let Some(&(_, d)) = chars.get(i) {
if d.is_whitespace() || matches!(d, ';' | '|' | '&' | '(' | ')' | '<' | '>') {
break;
}
if !matches!(d, '\'' | '"' | '\\') {
delim.push(d);
}
i += 1;
}
pending.push(delim);
word_start = false;
continue;
}
(In::Paren, '\n') if !pending.is_empty() => {
for delim in std::mem::take(&mut pending) {
loop {
let start = i + 1;
if start >= chars.len() {
i = chars.len();
break;
}
let mut j = start;
while j < chars.len() && chars[j].1 != '\n' {
j += 1;
}
let text = &line[end_of(start)..end_of(j)];
i = j;
if text.trim_start_matches('\t') == delim {
break;
}
}
}
}
_ => {}
}
word_start = c.is_whitespace() || matches!(c, ';' | '|' | '&' | '(');
i += 1;
}
end_of(i).max(chars[at].0) - chars[at].0
}
#[allow(clippy::too_many_lines, unused_assignments)]
fn raw_commands(line: &str) -> Vec<RawCommand> {
#[derive(PartialEq, Eq)]
enum Target {
None,
File,
Heredoc { strip_tabs: bool },
HereString,
}
let chars: Vec<(usize, char)> = line.char_indices().collect();
let end_of = |i: usize| chars.get(i).map_or(line.len(), |c| c.0);
let code_of = |open: usize, len: usize| -> Option<String> {
let (start, c) = chars[open];
let stop = (start + len).min(line.len());
let close = line[..stop].chars().next_back();
let inner_end = if close == Some(if c == '`' { '`' } else { ')' }) && stop > start + 1 {
stop - 1
} else {
stop
};
matches!(c, '(' | '`').then(|| line[start + 1..inner_end.max(start + 1)].to_string())
};
let comments = crate::parser::hash_comments();
let mut cmds: Vec<RawCommand> = Vec::new();
let mut cur = RawCommand::default();
let mut word = RawWord {
plain: true,
..RawWord::default()
};
let mut in_word = false;
let mut quoted_parts = 0usize;
let mut other_parts = false;
let mut target = Target::None;
let mut pending: Vec<(String, bool, Option<usize>)> = Vec::new();
let mut i = 0;
macro_rules! finish_word {
() => {
if in_word {
let mut w = std::mem::replace(
&mut word,
RawWord {
plain: true,
..RawWord::default()
},
);
if quoted_parts != 1 || other_parts {
w.single_quoted = None;
}
if matches!(w.text.as_str(), "{" | "}") {
w.plain = true;
}
match std::mem::replace(&mut target, Target::None) {
Target::None => cur.words.push(w),
Target::File => {}
Target::Heredoc { strip_tabs } => {
let delim: String = w
.text
.chars()
.filter(|c| !matches!(c, '\'' | '"' | '\\'))
.collect();
pending.push((delim, strip_tabs, None));
}
Target::HereString => cur.stdin.push(
w.single_quoted
.clone()
.unwrap_or_else(|| w.text.trim_matches(['\'', '"']).to_string()),
),
}
}
in_word = false;
quoted_parts = 0;
other_parts = false;
};
}
macro_rules! finish_command {
($at:expr) => {
finish_word!();
if !cur.words.is_empty() || !cur.stdin.is_empty() {
cur.end = $at;
let idx = cmds.len();
for p in &mut pending {
if p.2.is_none() {
p.2 = Some(idx);
}
}
cmds.push(std::mem::take(&mut cur));
} else {
pending.retain(|p| p.2.is_some());
}
};
}
while i < chars.len() {
let (at, c) = chars[i];
match c {
'\\' if chars.get(i + 1).is_some_and(|n| n.1 == '\n') => {
i += 2;
continue;
}
'\\' => {
in_word = true;
other_parts = true;
word.plain = false;
word.text.push_str(&line[at..end_of(i + 2)]);
i += 2;
continue;
}
'\'' => {
let mut j = i + 1;
while j < chars.len() && chars[j].1 != '\'' {
j += 1;
}
in_word = true;
quoted_parts += 1;
word.plain = false;
word.single_quoted = Some(line[end_of(i + 1)..end_of(j)].to_string());
word.text.push_str(&line[at..end_of(j + 1)]);
i = j + 1;
continue;
}
'"' => {
let mut j = i + 1;
while j < chars.len() && chars[j].1 != '"' {
match chars[j].1 {
'\\' => j += 1,
'`' => {
let len = nested_len(&chars, j, line);
cur.substitutions.extend(code_of(j, len));
j = chars.partition_point(|x| x.0 < chars[j].0 + len);
continue;
}
'$' if chars.get(j + 1).is_some_and(|n| matches!(n.1, '(' | '{')) => {
let len = nested_len(&chars, j + 1, line);
cur.substitutions.extend(code_of(j + 1, len));
j = chars.partition_point(|x| x.0 < chars[j + 1].0 + len);
continue;
}
_ => {}
}
j += 1;
}
in_word = true;
other_parts = true;
word.plain = false;
word.text.push_str(&line[at..end_of(j + 1)]);
i = j + 1;
continue;
}
'$' if chars.get(i + 1).is_some_and(|n| n.1 == '\'') => {
let mut j = i + 2;
while j < chars.len() && chars[j].1 != '\'' {
if chars[j].1 == '\\' {
j += 1;
}
j += 1;
}
in_word = true;
other_parts = true;
word.plain = false;
word.text.push_str(&line[at..end_of(j + 1)]);
i = j + 1;
continue;
}
'$' | '`' => {
let open = if c == '`' { i } else { i + 1 };
let len = match chars.get(open).map(|n| n.1) {
Some('(' | '{' | '`') => nested_len(&chars, open, line),
_ => 0,
};
if len > 0 {
cur.substitutions.extend(code_of(open, len));
}
let stop = if len == 0 {
end_of(i + 1)
} else {
chars[open].0 + len
};
in_word = true;
other_parts = true;
word.plain = false;
word.text.push_str(&line[at..stop]);
i = chars.partition_point(|x| x.0 < stop);
continue;
}
'#' if !in_word && comments => {
while i < chars.len() && chars[i].1 != '\n' {
i += 1;
}
continue;
}
'(' if in_word && word.text.ends_with('=') => {
let len = nested_len(&chars, i, line);
word.plain = false;
word.text.push_str(&line[at..at + len]);
other_parts = true;
i = chars.partition_point(|x| x.0 < at + len);
continue;
}
'<' | '>' if chars.get(i + 1).is_some_and(|n| n.1 == '(') => {
let len = nested_len(&chars, i + 1, line);
cur.substitutions.extend(code_of(i + 1, len));
in_word = true;
other_parts = true;
word.plain = false;
word.text.push_str(&line[at..chars[i + 1].0 + len]);
i = chars.partition_point(|x| x.0 < chars[i + 1].0 + len);
continue;
}
'<' | '>' => {
if in_word && word.text.chars().all(|d| d.is_ascii_digit()) {
in_word = false;
word = RawWord {
plain: true,
..RawWord::default()
};
quoted_parts = 0;
other_parts = false;
} else {
finish_word!();
}
let rest: String = chars[i..].iter().take(3).map(|x| x.1).collect();
let (len, kind) = if rest.starts_with("<<<") {
(3, Target::HereString)
} else if rest.starts_with("<<-") {
(3, Target::Heredoc { strip_tabs: true })
} else if rest.starts_with("<<") {
(2, Target::Heredoc { strip_tabs: false })
} else if rest.starts_with(">>")
|| rest.starts_with(">&")
|| rest.starts_with("<&")
|| rest.starts_with(">|")
|| rest.starts_with("<>")
{
(2, Target::File)
} else {
(1, Target::File)
};
target = kind;
i += len;
continue;
}
'&' if chars.get(i + 1).is_some_and(|n| n.1 == '>') => {
finish_word!();
target = Target::File;
i += if chars.get(i + 2).is_some_and(|n| n.1 == '>') {
3
} else {
2
};
continue;
}
';' | '&' | '|' | '(' | ')' | '\n' => {
finish_command!(at);
cur.piped = c == '|'
&& chars.get(i + 1).is_none_or(|n| n.1 != '|')
&& (i == 0 || chars[i - 1].1 != '|');
if c == '\n' && !pending.is_empty() {
let mut j = i;
for (delim, strip_tabs, idx) in std::mem::take(&mut pending) {
let mut body = String::new();
loop {
let start = j + 1;
if start >= chars.len() {
j = chars.len();
break;
}
let mut k = start;
while k < chars.len() && chars[k].1 != '\n' {
k += 1;
}
let text = &line[end_of(start)..end_of(k)];
j = k;
let cmp = if strip_tabs {
text.trim_start_matches('\t')
} else {
text
};
if cmp == delim {
break;
}
body.push_str(text);
body.push('\n');
}
if let Some(cmd) = idx.and_then(|n| cmds.get_mut(n)) {
cmd.stdin.push(body);
}
}
i = j + 1;
continue;
}
i += 1;
continue;
}
c if c.is_whitespace() => {
finish_word!();
}
_ => {
in_word = true;
other_parts = true;
if matches!(c, '*' | '?' | '[' | '{' | '}' | '~') {
word.plain = false;
}
word.text.push(c);
}
}
i += 1;
}
finish_command!(line.len());
cmds
}
#[allow(clippy::too_many_lines)]
fn command_word(words: &[RawWord]) -> Option<usize> {
static ASSIGN: OnceLock<Regex> = OnceLock::new();
let assign = ASSIGN.get_or_init(|| {
Regex::new(r"^[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=").expect("valid regex")
});
let lit = |i: usize| words.get(i).filter(|w| w.plain).map(|w| w.text.as_str());
let num = |w: &str| {
let w = w.trim_start_matches(['-', '+']);
!w.is_empty() && w.chars().all(|c| c.is_ascii_digit() || c == '.')
};
let duration = |w: &str| {
let d = w.trim_end_matches(['s', 'm', 'h', 'd']);
num(d) && !d.starts_with(['-', '+'])
};
let mut i = 0;
loop {
let word = words.get(i)?;
if assign.is_match(&word.text) {
i += 1;
continue;
}
let Some(w) = lit(i) else {
return Some(i);
};
match w {
"then" | "do" | "else" | "elif" | "if" | "while" | "until" | "!" | "{" | "}" | "fi"
| "done" | "esac" | "nohup" | "exec" => i += 1,
"time" => {
i += 1;
if lit(i) == Some("-p") {
i += 1;
}
}
"command" => {
i += 1;
match lit(i) {
Some("-p") => i += 1,
Some(o) if o.starts_with('-') => return Some(i - 1),
_ => {}
}
}
"nice" => {
i += 1;
if lit(i) == Some("-n") && lit(i + 1).is_some_and(num) {
i += 2;
}
}
"env" => {
let at = i;
i += 1;
loop {
match lit(i) {
Some("-i" | "-" | "--ignore-environment") => i += 1,
Some("-u" | "--unset") if lit(i + 1).is_some() => i += 2,
Some(o)
if o.starts_with("--unset=")
|| (o.starts_with("-u") && o.len() > 2) =>
{
i += 1;
}
Some(o) if o.starts_with('-') => return Some(at),
_ if words.get(i).is_some_and(|w| assign.is_match(&w.text)) => i += 1,
_ => break,
}
}
}
"timeout" => {
let at = i;
i += 1;
loop {
match lit(i) {
Some("--foreground" | "--preserve-status") => i += 1,
Some("-s" | "--signal" | "-k" | "--kill-after") if lit(i + 1).is_some() => {
i += 2;
}
Some(o)
if o.starts_with("--signal=")
|| o.starts_with("--kill-after=")
|| ((o.starts_with("-s") || o.starts_with("-k"))
&& o.len() > 2) =>
{
i += 1;
}
Some(d) if duration(d) => {
i += 1;
break;
}
_ => return Some(at),
}
}
}
"stdbuf" => {
let at = i;
i += 1;
loop {
match lit(i) {
Some("-i" | "-o" | "-e") if lit(i + 1).is_some() => i += 2,
Some(o)
if (o.len() > 2
&& (o.starts_with("-i")
|| o.starts_with("-o")
|| o.starts_with("-e")))
|| o.starts_with("--input=")
|| o.starts_with("--output=")
|| o.starts_with("--error=") =>
{
i += 1;
}
Some(o) if o.starts_with('-') => return Some(at),
_ => break,
}
}
}
"ionice" => {
let at = i;
i += 1;
loop {
match lit(i) {
Some("-c" | "-n") if lit(i + 1).is_some_and(num) => i += 2,
Some(o)
if o.len() > 2
&& (o.starts_with("-c") || o.starts_with("-n"))
&& num(&o[2..]) =>
{
i += 1;
}
Some(o) if o.starts_with('-') => return Some(at),
_ => break,
}
}
}
_ => return Some(i),
}
}
}
fn privileged_shell_reads_stdin(words: &[RawWord]) -> bool {
const SHELLS: &[&str] = &["sh", "bash", "zsh", "dash", "ksh", "fish", "su"];
let text: Vec<&str> = words.iter().map(|w| w.text.as_str()).collect();
let base = |w: &str| w.rsplit('/').next().unwrap_or_default().to_string();
let Some(first) = text.first().map(|w| base(w)) else {
return false;
};
let su_shell = |rest: &[&str]| {
!rest
.iter()
.any(|w| matches!(*w, "-c" | "--command" | "-C") || w.starts_with("--command="))
};
match first.as_str() {
"su" => su_shell(&text[1..]),
"machinectl" => text.get(1) == Some(&"shell") && text.len() <= 3,
"sudo" | "doas" | "run0" | "sudo-rs" | "please" | "pkexec" | "runuser" => {
let mut i = 1;
let mut shell_flag = false;
while let Some(w) = text.get(i) {
if *w == "--" {
i += 1;
break;
}
if !w.starts_with('-') {
break;
}
if w.starts_with("--") {
shell_flag |= matches!(*w, "--shell" | "--login");
} else {
shell_flag |= w[1..]
.chars()
.take_while(|c| !"ugCDhprtTU".contains(*c))
.any(|c| matches!(c, 's' | 'i'));
}
let (n, _) = crate::parser::privilege_option(w, text.get(i + 1).copied());
i += n;
}
text.get(i).map_or(
shell_flag || matches!(first.as_str(), "run0" | "pkexec"),
|cmd| {
let cmd = base(cmd);
SHELLS.contains(&cmd.as_str())
&& (cmd == "su" && su_shell(&text[i + 1..])
|| cmd != "su" && !text[i + 1..].iter().any(|w| w.starts_with("-c")))
},
)
}
_ => false,
}
}
fn leading_word(re: &str) -> Option<String> {
let re = re
.strip_prefix(r"(?:shellfirm-privileged\s+)?")
.unwrap_or(re);
let re = re.strip_prefix(r"shellfirm-privileged\s+").unwrap_or(re);
let word: String = re
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
.collect();
(!word.is_empty() && re[word.len()..].starts_with(r"\s")).then_some(word)
}
fn position_sensitive_words() -> Option<&'static (Vec<String>, Vec<String>)> {
static WORDS: OnceLock<Option<(Vec<String>, Vec<String>)>> = OnceLock::new();
WORDS
.get_or_init(|| {
let mut all: Vec<String> = Vec::new();
let mut named: Vec<String> = Vec::new();
let marker = format!("{PRIVILEGED_MARKER}\\s+");
for check in all_checks_cached() {
if PRIVILEGE_SURVIVORS.contains(&check.id.as_str()) {
continue;
}
for f in &check.filters {
if let Filter::NotMatches(re) = f {
if let Some(re) = re.strip_prefix('^') {
let word = leading_word(re)?;
if !all.contains(&word) {
all.push(word);
}
}
}
}
let test = check.test.as_str();
for (at, _) in test.match_indices(&marker) {
let word = leading_word(&test[at..])?;
if !named.contains(&word) {
named.push(word.clone());
}
if !all.contains(&word) {
all.push(word);
}
}
}
Some((all, named))
})
.as_ref()
}
const MAX_PREFIX_PARSES: usize = 32;
const MAX_PREFIX_PARSE_BYTES: usize = 16 * 1024;
#[derive(Default)]
struct Position {
own: std::collections::HashSet<String>,
tainted: std::collections::HashSet<String>,
shell_stdin: Vec<String>,
arguments: Vec<String>,
}
fn defined_names(command: &str) -> Vec<String> {
static DEF: OnceLock<Regex> = OnceLock::new();
let def = DEF.get_or_init(|| {
Regex::new(
r"(?:^|[\s;&|(){}])(?:function\s+([^\s;&|(){}<>=]+)|([^\s;&|(){}<>='$`]+)\s*\(\s*\)|alias\s+(?:-\S+\s+)*([^\s;&|(){}<>=]+)=)",
)
.expect("valid regex")
});
if !command.contains("()") && !command.contains("function") && !command.contains("alias") {
return Vec::new();
}
def.captures_iter(command)
.filter_map(|c| c.get(1).or_else(|| c.get(2)).or_else(|| c.get(3)))
.map(|m| m.as_str().to_string())
.collect()
}
#[allow(clippy::too_many_lines)]
fn command_position(command: &str, segments: &[String], depth: usize, out: &mut Position) {
let cmds = raw_commands(command);
let defined = defined_names(command);
let mut before: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut start = 0;
let mut directory_unknown = false;
for (n, cmd) in cmds.iter().enumerate() {
let text = command.get(start..cmd.end).unwrap_or_default();
start = cmd.end;
let new: Vec<String> = if cmds.len() == 1 {
segments.to_vec()
} else if cmds.len() <= MAX_PREFIX_PARSES && command.len() <= MAX_PREFIX_PARSE_BYTES {
let upto: std::collections::HashSet<String> = crate::parser::parse(&command[..cmd.end])
.segments
.into_iter()
.collect();
let mut new: Vec<String> = upto.difference(&before).cloned().collect();
new.sort();
before = upto;
new
} else {
crate::parser::parse(text).segments
};
for code in &cmd.substitutions {
out.tainted.extend(crate::parser::parse(code).segments);
}
if directory_unknown {
out.tainted.extend(new);
out.tainted.extend(crate::parser::parse(text).segments);
continue;
}
let Some(at) = command_word(&cmd.words) else {
continue;
};
let rest = &cmd.words[at..];
let words_text = |ws: &[RawWord]| {
ws.iter()
.map(|w| w.text.as_str())
.collect::<Vec<_>>()
.join(" ")
};
let alone = if cmds.len() == 1 {
Vec::new()
} else {
crate::parser::parse(&words_text(rest)).segments
};
let w = &rest[0];
let unknown = !w.plain || defined.contains(&w.text);
if unknown || privileged_shell_reads_stdin(rest) {
let piped_in = n
.checked_sub(1)
.filter(|_| cmd.piped)
.and_then(|p| cmds.get(p))
.map_or(&[][..], |p| p.stdin.as_slice());
for code in cmd.stdin.iter().chain(piped_in) {
let segs = crate::parser::parse(code).segments;
out.tainted.extend(segs.iter().cloned());
out.shell_stdin.extend(segs);
}
}
if let Some((_, named)) = position_sensitive_words() {
for (k, word) in rest.iter().enumerate().skip(1).take(64) {
if word.plain && named.contains(&word.text) {
out.arguments
.extend(crate::parser::parse(&words_text(&rest[k..])).segments);
}
}
}
if unknown {
out.tainted.extend(alone);
out.tainted.extend(new);
continue;
}
let base = w.text.rsplit('/').next().unwrap_or_default();
directory_unknown = changes_to_unknown_directory(command, base, &rest[1..]);
if base == "rm" && rest[1..].iter().any(|w| !relative_as_written(w)) {
out.tainted.extend(alone);
out.tainted.extend(new);
continue;
}
let first = |s: &str| {
let f = s.split(' ').next().unwrap_or_default();
f == base || f == w.text
};
let literal_code = (matches!(base, "sh" | "bash" | "zsh" | "dash" | "ksh")
&& rest.len() == 3
&& rest[1].plain
&& rest[1].text == "-c"
&& depth < 4)
.then(|| rest[2].single_quoted.as_deref())
.flatten();
let mut sub = Position::default();
if let Some(code) = literal_code {
let inner = crate::parser::parse(code).segments;
command_position(code, &inner, depth + 1, &mut sub);
out.tainted.extend(sub.tainted.iter().cloned());
out.shell_stdin.extend(sub.shell_stdin.iter().cloned());
}
let rimraf = base == "npx"
&& rest[1..]
.iter()
.find(|w| !matches!(w.text.as_str(), "-y" | "--yes"))
.is_some_and(|w| w.plain && w.text == "rimraf")
&& rest.iter().all(|w| w.plain && relative_as_written(w));
for s in new.into_iter().chain(alone) {
if first(&s)
|| (rimraf && s.starts_with("rm "))
|| (sub.own.contains(&s) && !sub.tainted.contains(&s))
{
out.own.insert(s);
} else {
out.tainted.insert(s);
}
}
out.own.extend(sub.own);
}
}
fn changes_to_unknown_directory(command: &str, base: &str, args: &[RawWord]) -> bool {
let stack_index = |w: &str| {
w.strip_prefix(['+', '-'])
.is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
};
match base {
"popd" => true,
"cd" | "pushd" if command.contains("CDPATH") => true,
"cd" => args.iter().any(|w| w.text == "-" || stack_index(&w.text)),
"pushd" => args
.iter()
.all(|w| w.text.starts_with(['-', '+']) || stack_index(&w.text)),
_ => false,
}
}
fn relative_as_written(w: &RawWord) -> bool {
let t = w.text.as_str();
if t.starts_with('-') {
return true;
}
!t.contains(['$', '`', '\\']) && !t.trim_start_matches(['\'', '"']).starts_with(['~', '/'])
}
fn privileged_copies(command: &str, segments: &[String]) -> Vec<String> {
let parsed = crate::parser::parse(command);
let remote = &parsed.remote_segments;
let sensitive = |s: &str| {
position_sensitive_words().is_none_or(|(words, named)| {
let first = s.split(' ').next().unwrap_or_default();
words.iter().any(|w| w == first) || named.iter().any(|w| s.contains(&format!(" {w} ")))
})
};
let stdin_shell = command.contains("<<");
if !stdin_shell && !segments.iter().chain(remote.iter()).any(|s| sensitive(s)) {
return Vec::new();
}
let mut pos = Position::default();
command_position(command, segments, 0, &mut pos);
let _ = crate::parser::parse(command);
pos.tainted.extend(remote.iter().cloned());
let line: std::collections::HashSet<&String> = segments.iter().collect();
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut out: Vec<String> = Vec::new();
let mut push = |s: String, out: &mut Vec<String>| {
if seen.insert(s.clone()) {
out.push(s);
}
};
for s in &pos.arguments {
if !s.starts_with("shellfirm-") {
push(format!("{PRIVILEGED_MARKER} {s}"), &mut out);
}
}
for s in &pos.shell_stdin {
if !s.starts_with("shellfirm-") && !line.contains(s) {
push(s.clone(), &mut out);
}
}
for s in segments.iter().chain(&pos.shell_stdin) {
if !s.starts_with("shellfirm-") && (pos.tainted.contains(s) || !pos.own.contains(s)) {
push(format!("{PRIVILEGED_MARKER} {s}"), &mut out);
}
}
out
}
fn writes_to_file(seg: &str) -> bool {
let words: Vec<&str> = seg.split(' ').collect();
words.iter().enumerate().any(|(i, w)| {
w.contains('>')
&& !(matches!(*w, "2>&1" | ">/dev/null" | "2>/dev/null" | "&>/dev/null")
|| (*w == "2>&" && words.get(i + 1) == Some(&"1"))
|| (matches!(*w, ">" | "2>" | "&>") && words.get(i + 1) == Some(&"/dev/null")))
})
}
fn flat_steps(flat: &str) -> Vec<(String, &str)> {
let mut steps = Vec::new();
let mut cmd: Vec<&str> = Vec::new();
for w in flat.split(' ') {
if let Some(op) = ["&&", "||", ";", "|", "|&", "&"].iter().find(|o| **o == w) {
steps.push((cmd.join(" "), *op));
cmd.clear();
} else {
cmd.push(w);
}
}
steps.push((cmd.join(" "), ""));
steps
}
fn is_plain_git_step(seg: &str) -> bool {
if seg.contains("$(") || seg.contains('`') || seg.contains('<') || writes_to_file(seg) {
return false;
}
let words: Vec<&str> = seg.split(' ').filter(|w| !w.is_empty()).collect();
let ["git", sub, rest @ ..] = words.as_slice() else {
return false;
};
let (flags, valued, max_operands): (&[&str], &[&str], usize) = match *sub {
"pull" => (
&[
"--ff-only",
"--rebase",
"--no-rebase",
"-q",
"-v",
"--prune",
"--tags",
"--autostash",
],
&[],
2,
),
"fetch" => (&["--all", "--prune", "-p", "--tags", "-q", "-v"], &[], 2),
"checkout" => (&["-q"], &["-b"], 1),
"switch" => (&["-q"], &["-c", "-C"], 1),
"clone" => (
&["-q", "--single-branch"],
&["--depth", "-b", "--branch"],
2,
),
_ => return false,
};
let mut operands = 0;
let mut i = 0;
while let Some(w) = rest.get(i) {
if flags.contains(w) {
i += 1;
} else if valued.contains(w) {
if rest.get(i + 1).is_none_or(|v| v.starts_with('-')) {
return false;
}
i += 2;
} else if let Some((opt, v)) = w.split_once('=') {
if !valued.contains(&opt) || !opt.starts_with("--") || v.is_empty() {
return false;
}
i += 1;
} else if w.starts_with('-') {
return false;
} else {
if matches!(*sub, "fetch" | "pull")
&& (w.contains("::")
|| (operands == 1 && (w.starts_with(['+', '^']) || w.contains([':', '*']))))
{
return false;
}
operands += 1;
i += 1;
}
}
let needs_operand = matches!(*sub, "checkout" | "switch" | "clone");
operands <= max_operands && (!needs_operand || operands >= 1)
}
fn is_velero_restore_print(seg: &str) -> bool {
let words: Vec<&str> = seg.split(' ').collect();
words.first() == Some(&"velero")
&& words
.windows(2)
.any(|p| p == ["restore", "create"] || p == ["create", "restore"])
&& words
.iter()
.any(|w| w.starts_with("-o") || w.starts_with("--output"))
}
fn is_inspection_segment(seg: &str) -> bool {
if seg.contains("$(") || seg.contains('`') || seg.contains("<(") || seg.contains(">(") {
return false;
}
if writes_to_file(seg) {
return false;
}
let words: Vec<&str> = seg.split(' ').collect();
match words.as_slice() {
["git", sub, ..] => matches!(*sub, "diff" | "status" | "log" | "show" | "add"),
["rg", rest @ ..] => !rest.iter().any(|w| w.starts_with("--pre")),
["less" | "more", rest @ ..] => !rest.iter().any(|w| w.starts_with('+')),
[first, ..] => matches!(
*first,
"cd" | "cat"
| "head"
| "tail"
| "wc"
| "grep"
| "egrep"
| "fgrep"
| "diff"
| "cmp"
| "ls"
| "echo"
| "printf"
| "true"
| "pwd"
),
[] => true,
}
}
fn is_submodule_update(seg: &str) -> bool {
seg.starts_with("git submodule update")
}
fn submodule_step_unsafe(command: &str, segments: &[String], steps: &[(String, &str)]) -> bool {
static GIT_GLOBAL: OnceLock<Regex> = OnceLock::new();
let git_global = GIT_GLOBAL.get_or_init(|| {
Regex::new(r"(?:^|[^\w./-])git\s+-|(?:^|[^\w])GIT_[A-Z_]*=").expect("valid regex")
});
let nested = steps
.iter()
.any(|(c, _)| !is_submodule_update(c) && c.contains("submodule"));
let before_ok = match steps.iter().rposition(|(c, _)| is_submodule_update(c)) {
Some(last) if !nested => steps[..last].iter().all(|(c, _)| {
is_submodule_update(c) || is_inspection_segment(c) || is_plain_git_step(c)
}),
_ => segments
.iter()
.all(|s| is_submodule_update(s) || is_inspection_segment(s)),
};
git_global.is_match(command)
|| !before_ok
|| segments.iter().any(|s| s.starts_with("git submodule foreach"))
|| steps.iter().any(|(_, op)| matches!(*op, "&" | "|&"))
|| steps
.iter()
.any(|(cmd, op)| is_submodule_update(cmd) && *op == "|")
|| crate::context::parse_command_targets(command)
.segments
.iter()
.any(|t| t.text.contains("submodule") && !t.text.starts_with("git submodule"))
}
fn velero_output_used(segments: &[String], steps: &[(String, &str)]) -> bool {
let piped = steps.iter().enumerate().any(|(i, (cmd, op))| {
is_velero_restore_print(cmd)
&& (matches!(*op, "&" | "|&")
|| (*op == "|"
&& !steps
.get(i + 1)
.is_some_and(|(next, _)| is_inspection_segment(next))))
});
let to_file = segments
.iter()
.any(|s| is_velero_restore_print(s) && writes_to_file(s));
let others_inspect = segments
.iter()
.all(|s| is_velero_restore_print(s) || is_inspection_segment(s));
piped || (to_file && !others_inspect)
}
fn line_context_segments(command: &str, segments: &[String]) -> Vec<String> {
static FIND_UP: OnceLock<Regex> = OnceLock::new();
let mut out = Vec::new();
let mut quoted = Vec::new();
quoted_dry_run_words(command, 0, &mut quoted);
quoted.retain(|w| {
w.to_ascii_lowercase().contains("dry")
|| segments.iter().any(|s| is_velero_restore_print(s))
});
if !quoted.is_empty() {
for seg in segments {
let is_quoted = |w: &str| {
quoted.iter().any(|q| {
q == w
&& (q.to_ascii_lowercase().contains("dry") || is_velero_restore_print(seg))
})
};
if seg.split(' ').any(is_quoted) {
let copy: Vec<String> = seg
.split(' ')
.map(|w| {
if is_quoted(w) {
format!("'{w}'")
} else {
w.to_string()
}
})
.collect();
out.push(copy.join(" "));
}
}
}
let submodule = segments.iter().any(|s| is_submodule_update(s));
let velero = segments.iter().any(|s| is_velero_restore_print(s));
if submodule || velero {
let flat = crate::parser::parse(command).flat;
let steps = flat_steps(&flat);
if submodule && submodule_step_unsafe(command, segments, &steps) {
out.extend(
segments
.iter()
.filter(|s| is_submodule_update(s))
.map(|s| format!("{LINE_CONTEXT_MARKER} {s}")),
);
}
if velero && velero_output_used(segments, &steps) {
out.extend(
segments
.iter()
.filter(|s| is_velero_restore_print(s))
.map(|s| format!("{LINE_CONTEXT_MARKER} {s}")),
);
}
}
out.extend(privileged_copies(command, segments));
let find_up = FIND_UP.get_or_init(|| {
Regex::new(r"(?:^|[\s;&|(])find\s+(?:-[HLP]\s+)*\S*\.\.").expect("valid regex")
});
if find_up.is_match(command) {
out.extend(
segments
.iter()
.filter(|s| s.starts_with("find "))
.map(|s| format!("{LINE_CONTEXT_MARKER} {s}")),
);
}
out
}
fn spell_linked_operands(env: &dyn Environment, command: &str, segments: &mut Vec<String>) {
let Ok(cwd) = env.current_dir() else {
return;
};
let home = env.home_dir();
let is_link = |p: &std::path::Path| std::fs::symlink_metadata(p).is_ok_and(|m| m.is_symlink());
let mut added = Vec::new();
for seg in segments.iter() {
let mut words: Vec<String> = seg.split(' ').map(crate::parser::desentinel).collect();
let mut changed = false;
match words.first().map(String::as_str) {
Some("rm") => {
for w in words.iter_mut().skip(1) {
if w.starts_with('-') {
continue;
}
let (base, rel) = match w.strip_prefix("~/") {
Some(rest) => match home.as_deref() {
Some(h) => (h.to_path_buf(), rest),
None => continue,
},
None if w.starts_with('/') => continue,
None => (cwd.clone(), w.as_str()),
};
let parts: Vec<&str> = rel.split('/').collect();
let Some(from) = parts.iter().position(|p| SKIPPED_CACHE_DIRS.contains(p))
else {
continue;
};
let mut path = base;
let mut linked = false;
for (i, part) in parts.iter().enumerate() {
path.push(part);
linked |= i >= from && is_link(&path);
}
if linked || written_with_trailing_slash(command, w) {
w.push('/');
changed = true;
}
}
}
Some("chmod") if words.len() == 3 => {
let op = &words[2];
if op.starts_with('.') && !op.contains('/') {
let path = cwd.join(op);
let not_a_file = std::fs::symlink_metadata(&path)
.is_ok_and(|m| m.is_dir() || m.is_symlink());
if not_a_file || written_with_trailing_slash(command, op) {
words[2].push('/');
changed = true;
}
}
}
_ => {}
}
if changed {
added.push(words.join(" "));
}
}
segments.extend(added);
}
fn spell_own_user(env: &dyn Environment, segments: &mut [String]) {
const SELF: &[&str] = &[
"$(whoami)",
"$(id -un)",
"$(id -nu)",
"$(id -u -n)",
"$(id -u)",
"$(logname)",
"`whoami`",
"`id -un`",
"`id -u`",
"$USER",
"${USER}",
"$LOGNAME",
"${LOGNAME}",
];
const GROUPS: &[&str] = &[
"$(id -g)",
"$(id -gn)",
"$(id -ng)",
"$(id -g -n)",
"`id -g`",
"`id -gn`",
];
if !segments.iter().any(|s| s.starts_with("chown ")) {
return;
}
let Some(user) = policy::current_user_name(env) else {
return;
};
let root = env.effective_uid() == Some(0);
let uid = env.effective_uid().map(|u| u.to_string());
for seg in segments.iter_mut().filter(|s| s.starts_with("chown ")) {
let mut start = "chown ".len();
while seg[start..].starts_with('-') {
match seg[start..].find(' ') {
Some(sp) => start += sp + 1,
None => break,
}
}
let rest = crate::parser::desentinel(&seg[start..]);
let (name, mut after) = SELF.iter().find(|p| rest.starts_with(**p)).map_or_else(
|| {
let end = rest.find([':', '.', ' ']).unwrap_or(rest.len());
(rest[..end].to_string(), end)
},
|p| ((*p).to_string(), p.len()),
);
let is_self = name == user
|| (SELF.contains(&name.as_str()) && !(root && name == "$(id -u)"))
|| (uid.as_deref() == Some(name.as_str()) && name != "0");
if !is_self {
continue;
}
if rest[after..].starts_with([':', '.']) {
let g = &rest[after + 1..];
after += 1 + GROUPS
.iter()
.find(|p| g.starts_with(**p))
.map_or_else(|| g.find(' ').unwrap_or(g.len()), |p| p.len());
}
if !(rest.len() == after || rest[after..].starts_with(' ')) {
continue;
}
let group = rest[name.len()..after].replace(' ', &crate::parser::WS_SENTINEL.to_string());
*seg = format!("{}$USER{group}{}", &seg[..start], &seg[start + after..]);
}
}
const MAX_GLOB_CANDIDATES: usize = 128;
const CRITICAL_GLOB_NAMES: &[&str] = &[
".ssh",
".gnupg",
".aws",
".kube",
".azure",
".docker",
".password-store",
".config",
".git",
".bashrc",
".zshrc",
".profile",
];
fn bracket_candidates(word: &str) -> Option<Vec<String>> {
let chars: Vec<char> = word.chars().collect();
let mut parts: Vec<Vec<char>> = Vec::new();
let mut has_class = false;
let mut i = 0;
while i < chars.len() {
if chars[i] == '[' {
if let Some(close) = chars[i + 1..]
.iter()
.skip(1)
.position(|c| *c == ']')
.map(|p| i + 2 + p)
{
let class = &chars[i + 1..close];
let (negate, class) = match class.split_first() {
Some(('!' | '^', r)) => (true, r),
_ => (false, class),
};
let mut set: Vec<char> = Vec::new();
let mut k = 0;
while k < class.len() {
if k + 2 < class.len() && class[k + 1] == '-' {
let (a, b) = (u32::from(class[k]), u32::from(class[k + 2]));
if b < a || b - a > 128 {
return None;
}
set.extend((a..=b).filter_map(char::from_u32));
k += 3;
} else {
set.push(class[k]);
k += 1;
}
}
if negate {
set = (0x21u32..0x7f)
.filter_map(char::from_u32)
.filter(|c| !set.contains(c) && *c != '/')
.collect();
}
parts.push(set);
has_class = true;
i = close + 1;
continue;
}
}
parts.push(vec![chars[i]]);
i += 1;
}
if !has_class {
return None;
}
let mut out = vec![String::new()];
for set in parts {
if out.len().saturating_mul(set.len()) > MAX_GLOB_CANDIDATES {
return None;
}
out = out
.iter()
.flat_map(|p| set.iter().map(move |c| format!("{p}{c}")))
.collect();
}
Some(out)
}
fn glob_resolved_segments(env: &dyn Environment, parsed: &crate::parser::Parsed) -> Vec<String> {
let home = env.home_dir();
let cwd = env.current_dir().ok();
let resolve = |p: &str| -> std::path::PathBuf {
match (p.strip_prefix('~'), &home) {
(Some(rest), Some(h)) if rest.is_empty() || rest.starts_with('/') => {
h.join(rest.trim_start_matches('/'))
}
_ => cwd
.as_ref()
.map_or_else(|| std::path::PathBuf::from(p), |c| c.join(p)),
}
};
let mut out = Vec::new();
for seg in &parsed.segments {
if !seg.contains(['[', '*', '?']) || parsed.remote_segments.binary_search(seg).is_ok() {
continue;
}
let words: Vec<&str> = seg.split(' ').collect();
if !words.first().is_some_and(|p| RESOLVED_PROGRAMS.contains(p)) {
continue;
}
let mut changed = false;
let mut new_words: Vec<String> = Vec::with_capacity(words.len());
for (i, w) in words.iter().enumerate() {
let text = crate::parser::desentinel(w);
if i == 0 || text.starts_with('-') || text.contains('$') {
new_words.push((*w).to_string());
continue;
}
if !text.contains('[') {
if let Some(names) =
star_glob_candidates(env, &text, home.as_deref(), cwd.as_deref())
{
changed = true;
let sentinel = crate::parser::WS_SENTINEL.to_string();
new_words.extend(names.iter().map(|c| c.replace(' ', &sentinel)));
} else {
new_words.push((*w).to_string());
}
continue;
}
let existing: Vec<String> = bracket_candidates(&text)
.unwrap_or_default()
.into_iter()
.filter(|c| !c.contains(['*', '?']) && env.path_exists(&resolve(c)))
.collect();
let chosen = if existing.is_empty() {
let (dir, pattern) = text.rsplit_once('/').unwrap_or(("", text.as_str()));
CRITICAL_GLOB_NAMES
.iter()
.filter(|n| !dir.contains(['[', '*', '?']) && glob_matches(pattern, n))
.map(|n| {
if dir.is_empty() && !text.starts_with('/') {
(*n).to_string()
} else {
format!("{dir}/{n}")
}
})
.collect()
} else {
existing
};
if chosen.is_empty() {
new_words.push((*w).to_string());
} else {
changed = true;
let sentinel = crate::parser::WS_SENTINEL.to_string();
new_words.extend(chosen.iter().map(|c| c.replace(' ', &sentinel)));
}
}
if changed {
out.push(new_words.join(" "));
}
}
out
}
fn star_glob_candidates(
env: &dyn Environment,
text: &str,
home: Option<&std::path::Path>,
cwd: Option<&std::path::Path>,
) -> Option<Vec<String>> {
if !text.contains(['*', '?']) || text.contains(['{', '(', '\\']) {
return None;
}
if text.contains("**") {
let mut t = text.to_string();
while t.contains("**/") {
t = t.replace("**/", "");
}
let t = t.replace("**", "*");
let t = if t.is_empty() { "*".to_string() } else { t };
return (t != text).then(|| vec![crate::parser::normalize_path(&t)]);
}
let (root, spelled, rest): (std::path::PathBuf, String, &str) =
if let Some(r) = text.strip_prefix("~/") {
(home?.to_path_buf(), "~".to_string(), r)
} else if let Some(r) = text.strip_prefix('/') {
(std::path::PathBuf::from("/"), String::new(), r)
} else {
(cwd?.to_path_buf(), ".".to_string(), text)
};
let comps: Vec<&str> = rest.split('/').filter(|c| !c.is_empty()).collect();
let last = comps.last()?;
let home_dots = comps.as_slice() == [".*"] && spelled == "~";
if !home_dots
&& matches!(*last, "*" | ".*")
&& !comps[..comps.len() - 1]
.iter()
.any(|c| c.contains(['*', '?']))
{
return None;
}
let mut cands: Vec<(std::path::PathBuf, String)> = vec![(root, spelled)];
for (k, comp) in comps.iter().enumerate() {
let mut next = Vec::new();
for (real, shown) in &cands {
let join = |name: &str| {
let shown = match shown.as_str() {
"" => format!("/{name}"),
"." => name.to_string(),
s => format!("{s}/{name}"),
};
(real.join(name), shown)
};
if !comp.contains(['*', '?']) {
next.push(join(comp));
continue;
}
if !env.path_exists(real) {
continue;
}
let Ok(entries) = std::fs::read_dir(real) else {
continue;
};
for e in entries.flatten().take(4096) {
let name = e.file_name().to_string_lossy().to_string();
if glob_matches(comp, &name) {
next.push(join(&name));
}
}
}
if next.len() > MAX_GLOB_CANDIDATES {
return None;
}
if next.is_empty() {
if k + 1 != comps.len() {
return None;
}
let names: Vec<String> = CRITICAL_GLOB_NAMES
.iter()
.filter(|n| glob_matches(comp, n))
.flat_map(|n| {
cands.iter().map(move |(_, shown)| match shown.as_str() {
"" => format!("/{n}"),
"." => (*n).to_string(),
s => format!("{s}/{n}"),
})
})
.collect();
return (!names.is_empty()).then_some(names);
}
cands = next;
}
Some(cands.into_iter().map(|(_, s)| s).collect())
}
fn bare_in_flat(flat: &str, seg: &str) -> bool {
flat.match_indices(seg).any(|(i, _)| {
let before = flat[..i].trim_end();
before.is_empty()
|| ["&&", "||", ";", "\n", "(", "{", "then", "do", "else"]
.iter()
.any(|op| before.ends_with(op))
|| (before.ends_with('&') && !before.ends_with(">&"))
})
}
fn psql_reader_options(words: &[String], bare: bool) -> bool {
const BOOL_LONG: &[&str] = &[
"--no-password",
"--password",
"--no-psqlrc",
"--quiet",
"--no-align",
"--tuples-only",
"--expanded",
"--csv",
"--single-transaction",
"--echo-queries",
"--echo-all",
"--echo-errors",
];
const VALUE_LONG: &[&str] = &[
"--dbname",
"--username",
"--host",
"--port",
"--file",
"--command",
];
let on_error_stop = |v: &str| {
matches!(
v,
"ON_ERROR_STOP=1" | "ON_ERROR_STOP=on" | "ON_ERROR_STOP=true"
)
};
let mut i = 1;
while let Some(w) = words.get(i) {
let w = w.as_str();
i += 1;
if w == "<" || w == "-f" || w == "-c" || matches!(w, "-d" | "-U" | "-h" | "-p") {
i += 1;
continue;
}
if matches!(w, "-o" | "-L" | "--output" | "--log-file") {
if !bare {
return false;
}
i += 1;
continue;
}
if w.starts_with("--output=") || w.starts_with("--log-file=") {
if !bare {
return false;
}
continue;
}
if w == "-v" || w == "--set" || w == "--variable" {
if !words.get(i).is_some_and(|v| on_error_stop(v)) {
return false;
}
i += 1;
continue;
}
if let Some(v) = w
.strip_prefix("--set=")
.or_else(|| w.strip_prefix("--variable="))
.or_else(|| w.strip_prefix("-v"))
{
if !on_error_stop(v) {
return false;
}
continue;
}
if BOOL_LONG.contains(&w) || w.starts_with('>') || w.starts_with("2>") || w == "1" {
continue;
}
if let Some((name, _)) = w.split_once('=') {
if VALUE_LONG.contains(&name) {
continue;
}
return false;
}
if let Some(short) = w.strip_prefix('-').filter(|s| !s.starts_with('-')) {
let mut chars = short.chars();
match chars.next() {
Some('d' | 'U' | 'h' | 'p' | 'f') if !chars.as_str().is_empty() => continue,
Some('o' | 'L') if !chars.as_str().is_empty() => {
if !bare {
return false;
}
continue;
}
_ if !short.is_empty() && short.chars().all(|c| "wWXqAtxeab1".contains(c)) => {
continue;
}
_ => return false,
}
}
if w.starts_with('-') {
return false;
}
}
true
}
#[allow(clippy::too_many_lines)]
fn psql_script_unknown(text: &str) -> bool {
let chars: Vec<char> = text.chars().collect();
let mut i = 0;
let mut prev = ' ';
while i < chars.len() {
let c = chars[i];
match c {
'\'' | '"' => {
i += 1;
while i < chars.len() && chars[i] != c {
i += 1;
}
}
'-' if chars.get(i + 1) == Some(&'-') => {
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
}
'/' if chars.get(i + 1) == Some(&'*') => {
i += 2;
while i + 1 < chars.len() && !(chars[i] == '*' && chars[i + 1] == '/') {
i += 1;
}
i += 1;
}
'$' if prev != '\\' && !prev.is_alphanumeric() && prev != '_' => {
let mut j = i + 1;
while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
j += 1;
}
if chars.get(j) == Some(&'$') {
let tag: String = chars[i..=j].iter().collect();
let rest: String = chars[j + 1..].iter().collect();
let skip = rest.find(&tag).map_or_else(
|| rest.chars().count(),
|p| rest[..p].chars().count() + tag.chars().count(),
);
i = j + skip;
}
}
':' if prev != ':'
&& chars
.get(i + 1)
.is_some_and(|n| n.is_ascii_alphabetic() || matches!(n, '_' | '\'' | '"')) =>
{
return true;
}
'\\' => {
let mut j = i + 1;
while j < chars.len()
&& (chars[j].is_ascii_alphanumeric()
|| matches!(chars[j], '+' | '!' | '?' | '.'))
{
j += 1;
}
let name: String = chars[i + 1..j].iter().collect();
let mut k = j;
while k < chars.len() && chars[k] != '\n' && chars[k] != '\\' {
k += 1;
}
let args: String = chars[j..k].iter().collect();
let first = args.split_whitespace().next().unwrap_or_default();
let display = name.starts_with('d')
|| matches!(
name.as_str(),
"l" | "l+"
| "list"
| "list+"
| "conninfo"
| "x"
| "timing"
| "echo"
| "q"
| "quit"
| "i"
| "ir"
| "include"
| "include_relative"
)
|| (name == "pset" && first != "pager")
|| (matches!(name.as_str(), "c" | "connect")
&& args.split_whitespace().count() == 1)
|| (name == "set"
&& matches!(first, "ON_ERROR_STOP" | "ECHO" | "VERBOSITY" | "QUIET"));
if !display || args.contains(':') && args.contains(['\'', '"']) {
return true;
}
if args
.split(|c: char| !(c.is_alphanumeric() || c == ':' || c == '_'))
.any(|t| {
t.starts_with(':')
&& t.chars().nth(1).is_some_and(|n| n.is_ascii_alphabetic())
})
{
return true;
}
i = k;
prev = ' ';
continue;
}
_ => {}
}
prev = chars.get(i).copied().unwrap_or(' ');
i += 1;
}
false
}
struct SqlInput {
client: String,
file: String,
base: Option<std::path::PathBuf>,
depth: usize,
cd_dirs: Vec<std::path::PathBuf>,
}
const MAX_SQL_INCLUDE_DEPTH: usize = 8;
fn sql_includes(text: &str) -> Vec<(String, bool)> {
let mut out = Vec::new();
for line in text.lines() {
let mut parts = line.trim().splitn(2, char::is_whitespace);
let (Some(cmd), Some(arg)) = (parts.next(), parts.next()) else {
continue;
};
let relative = match cmd.to_ascii_lowercase().as_str() {
"\\i" | "\\include" | "\\." | "source" | ".read" | ":r" => false,
"\\ir" | "\\include_relative" => true,
_ => continue,
};
let f = arg
.trim()
.trim_end_matches(';')
.trim()
.trim_matches(['\'', '"']);
if !f.is_empty() && !f.starts_with('|') {
out.push((f.to_string(), relative));
}
}
out
}
const MAX_SQL_FILE_BYTES: usize = 16 * 1024 * 1024;
const SQL_CLIENTS: &[&str] = &["psql", "mysql", "mariadb", "sqlite3", "duckdb"];
#[derive(Default)]
struct SqlFiles {
segments: Vec<String>,
referenced: bool,
all_read: bool,
origins: Vec<(String, String)>,
unchecked_client: Option<String>,
too_large: Option<(String, u64)>,
timed_out: Option<String>,
stopped_at_critical: bool,
consumed: std::collections::HashSet<String>,
}
impl SqlFiles {
fn sql_from_file_description(&self, generic: &str, parsed_client: &str) -> String {
let client = self.unchecked_client.as_deref().unwrap_or(parsed_client);
if let Some((file, bytes)) = &self.too_large {
let mib = (bytes + 512 * 1024) / (1024 * 1024);
return format!(
"SQL from a file is not checked here: file too large to check ({mib} MiB): \
review the statements in {file} before running it."
);
}
let text = generic.replace("<client>", client);
match &self.timed_out {
Some(file) => text.replacen(
"SQL from a file is not checked here:",
&format!("SQL from a file is not checked here: {file} took too long to check;"),
1,
),
None => text,
}
}
}
fn line_sql_client(parsed: &crate::parser::Parsed) -> &'static str {
const CLIENTS: &[&str] = &[
"psql",
"mysql",
"mariadb",
"sqlite3",
"duckdb",
"sqlcmd",
"cqlsh",
"clickhouse-client",
"mongosh",
"mongo",
];
parsed
.segments
.iter()
.chain(std::iter::once(&parsed.flat))
.find_map(|s| {
s.split(|c: char| c.is_whitespace() || c == '|')
.find_map(|w| CLIENTS.iter().find(|c| **c == w).copied())
})
.unwrap_or("psql")
}
fn sqlcmd_script(text: &str) -> (String, Vec<String>) {
static GO: OnceLock<Option<Regex>> = OnceLock::new();
let go = GO.get_or_init(|| Regex::new(r"(?i)^go(?:\s+\d+)?\s*;?$").ok());
let mut sql = String::with_capacity(text.len());
let mut shell = Vec::new();
for line in text.lines() {
let t = line.trim();
let bang = t.strip_prefix("!!").or_else(|| {
t.strip_prefix(':')
.and_then(|r| r.trim_start().strip_prefix("!!"))
});
if let Some(cmd) = bang {
shell.extend(crate::parser::parse(cmd.trim()).segments);
sql.push_str(";\n");
} else if t.starts_with(':') || go.as_ref().is_some_and(|g| g.is_match(t)) {
sql.push_str(";\n");
} else {
sql.push_str(line);
sql.push('\n');
}
}
(sql, shell)
}
#[allow(clippy::too_many_lines)]
fn sql_file_segments(
env: &dyn Environment,
command: &str,
parsed: &crate::parser::Parsed,
stop_at: Option<&[Check]>,
) -> SqlFiles {
static STREAM: OnceLock<Option<Regex>> = OnceLock::new();
let mut out = SqlFiles {
all_read: true,
..SqlFiles::default()
};
let started = std::time::Instant::now();
let budget = std::time::Duration::from_millis(
blast_radius::budget_ms().max(crate::config::DEFAULT_BLAST_RADIUS_BUDGET_MS),
);
let critical: Vec<Check> = stop_at
.unwrap_or_default()
.iter()
.filter(|c| c.severity == Severity::Critical)
.cloned()
.collect();
let critical_index = if critical.is_empty() {
None
} else {
LiteralIndex::new(&critical)
};
let mut notice: Option<blast_radius::ProgressNotice> = None;
let home = env.home_dir();
let cwd = env.current_dir().ok();
let resolve = |p: &str| -> std::path::PathBuf {
match (p.strip_prefix('~'), &home) {
(Some(rest), Some(h)) if rest.is_empty() || rest.starts_with('/') => {
h.join(rest.trim_start_matches('/'))
}
_ => cwd
.as_ref()
.map_or_else(|| std::path::PathBuf::from(p), |c| c.join(p)),
}
};
let mut files: Vec<(String, String, Vec<std::path::PathBuf>)> = Vec::new();
let mut untrusted: std::collections::HashSet<String> = std::collections::HashSet::new();
if let Some(at) = command.find("PSQLRC=") {
if parsed
.segments
.iter()
.any(|s| s.split([' ', '|']).any(|w| w == "psql"))
{
let rc: String = command[at + "PSQLRC=".len()..]
.chars()
.take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|'))
.collect();
out.referenced = true;
out.all_read = false;
out.unchecked_client
.get_or_insert_with(|| "psql".to_string());
out.segments.push(format!("psql -c \\i {rc}"));
}
}
let mut cd_dirs: Vec<std::path::PathBuf> = Vec::new();
let mut last_client = parsed
.segments
.iter()
.find_map(|s| {
s.split(' ')
.next()
.filter(|p| SQL_CLIENTS.contains(p))
.map(str::to_string)
})
.unwrap_or_else(|| "psql".to_string());
let mut marks: Vec<(&String, usize)> = Vec::new();
for seg in &parsed.segments {
marks.push((seg, files.len()));
if parsed.remote_segments.binary_search(seg).is_ok() {
continue;
}
let words: Vec<String> = seg.split(' ').map(crate::parser::desentinel).collect();
let Some(prog) = words.first().map(String::as_str) else {
continue;
};
if matches!(prog, "cd" | "pushd") && words.len() == 2 {
let d = &words[1];
if !d.starts_with('-') && !d.contains(['$', '`', '*']) {
let base = cd_dirs.last().cloned().or_else(|| cwd.clone());
let dir = if d.starts_with('~') || d.starts_with('/') {
resolve(d)
} else {
base.map_or_else(|| std::path::PathBuf::from(d), |b| b.join(d))
};
if dir.as_os_str().len() <= 4096 && cd_dirs.len() < 256 {
cd_dirs.push(dir);
}
}
continue;
}
if matches!(
prog,
"sqlcmd" | "cqlsh" | "clickhouse-client" | "mongosh" | "mongo"
) {
let flags: &[&str] = match prog {
"sqlcmd" => &["-i", "--input-file"],
"clickhouse-client" => &["--queries-file"],
_ => &["-f", "--file"],
};
let mut i = 1;
while i < words.len() {
let w = words[i].as_str();
let value = if flags.contains(&w) {
i += 1;
words.get(i).cloned()
} else {
flags
.iter()
.find_map(|f| w.strip_prefix(&format!("{f}=")).map(str::to_string))
.or_else(|| {
(prog == "sqlcmd" && w.len() > 2 && w.starts_with("-i"))
.then(|| w[2..].to_string())
})
};
if let Some(v) = value {
for f in v.split(',').filter(|f| !f.is_empty()) {
files.push((prog.to_string(), f.to_string(), cd_dirs.clone()));
}
} else if matches!(prog, "mongosh" | "mongo")
&& !w.starts_with('-')
&& std::path::Path::new(w)
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("js"))
{
files.push((prog.to_string(), w.to_string(), cd_dirs.clone()));
}
i += 1;
}
continue;
}
if SQL_CLIENTS.contains(&prog) {
last_client = prog.to_string();
let named_before = files.len();
let trusted =
prog != "psql" || psql_reader_options(&words, bare_in_flat(&parsed.flat, seg));
let mut i = 1;
while i < words.len() {
let w = words[i].as_str();
let next = words.get(i + 1).cloned();
if matches!(w, "-c" | "--command" | "-e" | "--execute") {
if let (Some(meta), Some(f)) = (next.as_deref(), words.get(i + 2)) {
if matches!(
meta,
"\\i" | "\\ir" | "\\include" | "\\include_relative" | "source" | "\\."
) {
files.push((prog.to_string(), f.clone(), cd_dirs.clone()));
}
}
let one_word = seg.contains(crate::parser::WS_SENTINEL)
|| words.get(i + 2).is_some_and(|w| w.starts_with('-'));
if !one_word {
break;
}
i += 2;
continue;
}
match w {
"-f" | "--file" | "<" | ".read" | "-init" if next.is_some() => {
files.push((prog.to_string(), next.unwrap_or_default(), cd_dirs.clone()));
i += 1;
}
_ => {
if let Some(f) = w.strip_prefix("--file=").or_else(|| {
w.strip_prefix("-f")
.filter(|f| !f.is_empty() && prog == "psql")
}) {
files.push((prog.to_string(), f.to_string(), cd_dirs.clone()));
}
if let Some(sql) = w.strip_prefix("--init-command=") {
out.segments
.extend(crate::parser::sql_text_segments(prog, sql));
}
}
}
i += 1;
}
if !trusted {
untrusted.extend(files[named_before..].iter().map(|(_, f, _)| f.clone()));
}
} else if matches!(prog, ".once" | ".output" | ".import" | ".read" | ".excel")
&& words
.get(1)
.is_some_and(|w| w.trim_start_matches(['\'', '"']).starts_with('|'))
{
let rest = words[1..].join(" ");
let cmd = rest
.trim_matches(['\'', '"'])
.trim_start_matches('|')
.trim_end_matches(['\'', '"']);
let cmd = if prog == ".import" {
cmd.rsplit_once(' ').map_or(cmd, |(c, _)| c)
} else {
cmd
};
out.segments.extend(crate::parser::parse(cmd).segments);
} else if prog == ".read" && words.len() == 2 {
files.push(("sqlite3".to_string(), words[1].clone(), cd_dirs.clone()));
} else if matches!(
prog,
"\\i" | "\\ir" | "\\include" | "\\include_relative" | "source" | "\\."
) && words.len() == 2
&& (prog.starts_with('\\') || last_client != "psql")
{
files.push((
last_client.clone(),
words[1].trim_end_matches(';').to_string(),
cd_dirs.clone(),
));
}
}
let names: std::collections::HashSet<&str> = files.iter().map(|(_, f, _)| f.as_str()).collect();
for (n, (seg, at)) in marks.iter().enumerate() {
let next = marks.get(n + 1).map_or(files.len(), |m| m.1);
let names_a_file = seg
.split([' ', '=', crate::parser::WS_SENTINEL])
.any(|w| names.contains(w));
if next > *at || names_a_file {
out.consumed.insert((*seg).clone());
}
}
let mut seen = std::collections::HashSet::new();
let mut queue: std::collections::VecDeque<SqlInput> = files
.into_iter()
.map(|(client, file, cd_dirs)| SqlInput {
client,
file,
base: None,
depth: 0,
cd_dirs,
})
.collect();
'files: while let Some(SqlInput {
client,
file,
base,
depth,
cd_dirs,
}) = queue.pop_front()
{
if started.elapsed() > budget {
out.all_read = false;
out.timed_out.get_or_insert_with(|| file.clone());
out.unchecked_client.get_or_insert_with(|| client.clone());
out.segments.push(format!("psql -c \\i {file}"));
break;
}
if matches!(file.as_str(), "-" | "/dev/stdin") {
continue;
}
out.referenced = true;
let spelled = ["$HOME/", "${HOME}/"]
.iter()
.find_map(|p| file.strip_prefix(p))
.map_or_else(|| file.clone(), |rest| format!("~/{rest}"));
let path = match &base {
Some(b) if !spelled.starts_with(['/', '~']) => b.join(&spelled),
_ => resolve(&spelled),
};
let mut paths = vec![path];
if base.is_none() && !spelled.starts_with(['/', '~']) {
paths.extend(cd_dirs.iter().map(|d| d.join(&spelled)));
}
paths.retain(|p| seen.insert(p.clone()));
if paths.is_empty() {
continue;
}
let read = |path: &std::path::Path| -> Option<String> {
let regular = std::fs::metadata(path).map_or(true, |m| {
m.is_file() && m.len() <= MAX_SQL_FILE_BYTES as u64
});
(!spelled.contains(['$', '`', '*']) && regular)
.then(|| env.read_file(path).ok())
.flatten()
.filter(|t| t.len() <= MAX_SQL_FILE_BYTES)
};
if out.too_large.is_none() {
out.too_large = paths.iter().find_map(|p| {
std::fs::metadata(p)
.ok()
.filter(|m| m.is_file() && m.len() > MAX_SQL_FILE_BYTES as u64)
.map(|m| (file.clone(), m.len()))
});
}
if notice.is_none() {
notice = Some(blast_radius::start_progress_notice(format!(
"shellfirm: checking {file}{} (Ctrl-C cancels)",
crate::config::glyph("…", "...")
)));
}
let texts: Vec<(std::path::PathBuf, String)> = paths
.iter()
.filter_map(|p| read(p).map(|t| (p.clone(), t)))
.collect();
if client == "psql"
&& (untrusted.contains(&file) || texts.iter().any(|(_, t)| psql_script_unknown(t)))
{
out.all_read = false;
out.unchecked_client.get_or_insert_with(|| client.clone());
out.segments.push(format!("psql -c \\i {file}"));
}
if texts.is_empty() {
out.all_read = false;
out.unchecked_client.get_or_insert_with(|| client.clone());
out.segments.push(match client.as_str() {
"sqlite3" | "duckdb" => format!(".read {file}"),
c @ ("mysql" | "mariadb") => format!("{c} -e source {file}"),
_ => format!("psql -c \\i {file}"),
});
}
for (path, t) in texts {
let mut segs: Vec<String> = if matches!(client.as_str(), "mongosh" | "mongo") {
t.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with("//"))
.take(10_000)
.map(|l| format!("mongosh --eval {l}"))
.collect()
} else if client == "sqlcmd" {
let (sql, mut shell) = sqlcmd_script(&t);
shell.extend(crate::parser::sql_text_segments(&client, &sql));
shell
} else {
crate::parser::sql_text_segments(&client, &t)
};
let mut stop = false;
let mut over_budget = started.elapsed() > budget;
for (at, sg) in segs.iter().enumerate() {
if critical_index
.as_ref()
.is_some_and(|ix| !ix.matches(sg, env, false).is_empty())
{
segs.truncate(at + 1);
out.stopped_at_critical = true;
stop = true;
break;
}
if at % 4096 == 4095 && started.elapsed() > budget {
segs.truncate(at + 1);
over_budget = true;
break;
}
}
out.origins
.extend(segs.iter().map(|sg| (sg.clone(), file.clone())));
out.segments.extend(segs);
if stop {
break 'files;
}
if over_budget {
out.all_read = false;
out.timed_out.get_or_insert_with(|| file.clone());
out.unchecked_client.get_or_insert_with(|| client.clone());
out.segments.push(format!("psql -c \\i {file}"));
break 'files;
}
for (inc, relative) in sql_includes(&t) {
if depth + 1 > MAX_SQL_INCLUDE_DEPTH {
out.all_read = false;
out.unchecked_client.get_or_insert_with(|| client.clone());
out.segments.push(format!("psql -c \\i {inc}"));
break;
}
queue.push_back(SqlInput {
client: client.clone(),
file: inc,
base: relative
.then(|| path.parent().map(std::path::Path::to_path_buf))
.flatten(),
depth: depth + 1,
cd_dirs: cd_dirs.clone(),
});
}
}
}
let pipes_sql = parsed.flat.contains('|')
&& ["psql", "mysql", "mariadb", "sqlite3"]
.iter()
.any(|c| parsed.flat.contains(c));
if !pipes_sql {
return out;
}
let stream = STREAM.get_or_init(|| {
Regex::new(
r"(?:^|\s)(?:gunzip|gzip\s+-[a-z]*d|xz\s+-[a-z]*d|zstd\s+-[a-z]*d|bunzip2|unzip\s+-p|psql|mysql|mariadb)\b[^|;&\n]*\|\s*(psql|mysql|mariadb|sqlite3)\b",
)
.ok()
});
if let Some(c) = stream.as_ref().and_then(|r| r.captures(&parsed.flat)) {
out.referenced = true;
out.all_read = false;
out.unchecked_client
.get_or_insert_with(|| c.get(1).map_or("psql", |m| m.as_str()).to_string());
out.segments.push(format!(
"zcat - | {}",
c.get(1).map_or("psql", |m| m.as_str())
));
}
out
}
#[cfg(test)]
const ALL_CHECKS: &str = include_str!(concat!(env!("OUT_DIR"), "/all-checks.yaml"));
include!(concat!(env!("OUT_DIR"), "/builtin-checks.rs"));
struct BuiltinCheck {
id: &'static str,
test: &'static str,
description: &'static str,
from: &'static str,
challenge: Option<Challenge>,
filters: &'static [BuiltinFilter],
alternative: Option<&'static str>,
alternative_info: Option<&'static str>,
severity: Option<Severity>,
literals: &'static [&'static str],
}
#[allow(dead_code)]
enum BuiltinFilter {
PathExists(usize),
NotContains(&'static str),
Contains(&'static str),
NotMatches(&'static str),
Matches(&'static str),
}
impl BuiltinCheck {
fn to_check(&self) -> Check {
let filters = self
.filters
.iter()
.map(|f| match f {
BuiltinFilter::PathExists(n) => Filter::PathExists(*n),
BuiltinFilter::NotContains(s) => Filter::NotContains((*s).to_string()),
BuiltinFilter::Contains(s) => Filter::Contains((*s).to_string()),
BuiltinFilter::NotMatches(s) => Filter::NotMatches((*s).to_string()),
BuiltinFilter::Matches(s) => Filter::Matches((*s).to_string()),
})
.collect();
Check {
id: self.id.to_string(),
test: CheckRegex::lazy(
self.test.to_string(),
(!self.literals.is_empty()).then_some(self.literals),
),
description: self.description.to_string(),
from: self.from.to_string(),
challenge: self.challenge.unwrap_or_default(),
filters,
alternative: self.alternative.map(str::to_string),
alternative_info: self.alternative_info.map(str::to_string),
severity: self.severity.unwrap_or_default(),
}
}
}
#[derive(Clone)]
pub struct CheckRegex(Arc<CheckRegexInner>);
struct CheckRegexInner {
source: String,
prefilter: Option<&'static [&'static str]>,
compiled: OnceLock<Regex>,
}
impl CheckRegex {
pub fn new(pattern: &str) -> std::result::Result<Self, regex::Error> {
Regex::new(pattern).map(Self::from)
}
fn lazy(source: String, prefilter: Option<&'static [&'static str]>) -> Self {
Self(Arc::new(CheckRegexInner {
source,
prefilter,
compiled: OnceLock::new(),
}))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0.source
}
#[must_use]
pub fn regex(&self) -> &Regex {
self.0.compiled.get_or_init(|| {
Regex::new(&self.0.source).expect("built-in check regex is validated by build.rs")
})
}
fn is_match_prefiltered(&self, text: &str, folded: &str) -> bool {
if let Some(lits) = self.0.prefilter {
if !lits.iter().any(|l| folded.contains(l)) {
return false;
}
}
self.regex().is_match(text)
}
}
impl From<Regex> for CheckRegex {
fn from(re: Regex) -> Self {
let compiled = OnceLock::new();
let source = re.as_str().to_string();
let _ = compiled.set(re);
Self(Arc::new(CheckRegexInner {
source,
prefilter: None,
compiled,
}))
}
}
impl std::ops::Deref for CheckRegex {
type Target = Regex;
fn deref(&self) -> &Regex {
self.regex()
}
}
impl std::fmt::Debug for CheckRegex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Regex").field(&self.as_str()).finish()
}
}
impl serde::Serialize for CheckRegex {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> serde::Deserialize<'de> for CheckRegex {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
serde_regex::deserialize::<Regex, D>(deserializer).map(Self::from)
}
}
#[derive(Debug, Default, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
Info,
Low,
#[default]
Medium,
High,
Critical,
}
impl std::fmt::Display for Severity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Info => write!(f, "INFO"),
Self::Low => write!(f, "LOW"),
Self::Medium => write!(f, "MEDIUM"),
Self::High => write!(f, "HIGH"),
Self::Critical => write!(f, "CRITICAL"),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(tag = "type", content = "value")]
pub enum Filter {
PathExists(usize),
NotContains(String),
Contains(String),
NotMatches(String),
Matches(String),
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Check {
pub id: String,
pub test: CheckRegex,
pub description: String,
pub from: String,
#[serde(default)]
pub challenge: Challenge,
#[serde(default)]
pub filters: Vec<Filter>,
#[serde(default)]
pub alternative: Option<String>,
#[serde(default)]
pub alternative_info: Option<String>,
#[serde(default)]
pub severity: Severity,
}
pub(crate) fn all_checks_cached() -> &'static [Check] {
static CHECKS: OnceLock<Vec<Check>> = OnceLock::new();
CHECKS.get_or_init(|| BUILTIN_CHECKS.iter().map(BuiltinCheck::to_check).collect())
}
pub fn get_all() -> Result<Vec<Check>> {
Ok(all_checks_cached().to_vec())
}
pub fn load_custom_checks(checks_dir: &std::path::Path) -> Result<Vec<Check>> {
let mut custom_checks = Vec::new();
if !checks_dir.is_dir() {
return Ok(custom_checks);
}
let entries = std::fs::read_dir(checks_dir)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.extension().is_some_and(|e| e == "yaml" || e == "yml") {
let content = std::fs::read_to_string(&path)?;
let checks: Vec<Check> = serde_yaml::from_str(&content)?;
custom_checks.extend(checks);
}
}
Ok(custom_checks)
}
#[must_use]
pub fn validate_checks(checks: &[Check]) -> Vec<String> {
let mut warnings = Vec::new();
for check in checks {
let num_captures = check.test.captures_len(); for filter in &check.filters {
if let Filter::PathExists(group_idx) = filter {
if *group_idx >= num_captures {
warnings.push(format!(
"check {:?}: PathExists({}) references a capture group that \
does not exist (regex has {} groups including group 0)",
check.id, group_idx, num_captures
));
}
}
}
}
warnings
}
#[must_use]
#[allow(clippy::too_many_lines)]
pub fn build_challenge_display(
settings: &Settings,
resolved: &ResolvedSettings,
checks: &[&Check],
context: &RuntimeContext,
merged_policy: &MergedPolicy,
blast_radii: &[(String, BlastRadiusInfo)],
) -> DisplayContext {
let mut descriptions: Vec<String> = Vec::new();
let mut alternatives: Vec<AlternativeInfo> = Vec::new();
let mut check_ids: Vec<String> = Vec::new();
debug!(
"list of denied pattern ids {:?}",
settings.deny_patterns_ids
);
for check in checks {
if !descriptions.contains(&check.description) {
descriptions.push(check.description.clone());
}
if !check_ids.contains(&check.id) {
check_ids.push(check.id.clone());
}
if let Some(ref alt) = check.alternative {
let already_has = alternatives.iter().any(|a| a.suggestion == *alt);
if !already_has {
alternatives.push(AlternativeInfo {
suggestion: alt.clone(),
explanation: check.alternative_info.clone(),
});
}
}
}
let deny_reasons = context::deny_reasons(settings, checks, merged_policy);
let effective =
context::effective_challenge(settings, resolved, checks, context, merged_policy);
let severity_label = checks
.iter()
.map(|c| c.severity)
.max()
.map(|s| format!("{s}"));
let blast_radius_label = blast_radii
.iter()
.max_by_key(|(_, br)| br.scope)
.map(|(_, br)| {
format!(
"[{}] {} {}",
br.scope,
crate::config::glyph("—", "-"),
crate::config::ascii_fallback(&context::escape_invisible(&br.description))
)
});
let matched: Vec<crate::prompt::MatchedCheck> = {
let mut seen = std::collections::HashSet::new();
checks
.iter()
.filter(|c| seen.insert(c.id.as_str()))
.map(|c| crate::prompt::MatchedCheck {
id: c.id.clone(),
severity: c.severity.to_string(),
description: c.description.clone(),
})
.collect()
};
let enforced: Vec<&str> = check_ids
.iter()
.filter(|id| merged_policy.is_enforced(id))
.map(String::as_str)
.collect();
let label = |id: &str| {
merged_policy
.label_for(id)
.unwrap_or_else(|| "project policy (.shellfirm.yaml)".to_string())
};
let ignore_hint = if enforced.is_empty() {
ignore_hint(checks, context, !deny_reasons.is_empty())
} else if deny_reasons.is_empty() {
Some(format!(
"`{}` is enforced by the {}.",
enforced.join("`, `"),
label(enforced[0])
))
} else {
None
};
let deny_hint = if deny_reasons.is_empty() {
None
} else {
let personal: Vec<String> = check_ids
.iter()
.filter(|id| settings.deny_patterns_ids.contains(id) && !merged_policy.is_denied(id))
.cloned()
.collect();
let by_policy: Vec<&str> = check_ids
.iter()
.filter(|id| merged_policy.is_denied(id))
.map(String::as_str)
.collect();
let mut parts = Vec::new();
if !personal.is_empty() {
parts.push(crate::prompt::personal_deny_hint(&personal));
}
if !by_policy.is_empty() {
parts.push(format!(
"Only a change to {} can allow it.",
if by_policy.len() == 1 {
"that policy"
} else {
"those policies"
}
));
}
(!parts.is_empty()).then(|| parts.join(" "))
};
let mut notes = Vec::new();
let esc = &settings.context.escalation;
let defaults = context::EscalationConfig::default();
match context.risk_level {
context::RiskLevel::Critical if defaults.critical.is_stricter_than(esc.critical) => {
notes.push(format!(
"Note: context escalation for critical contexts is set to {} (default {}), so production / root / protected-branch commands ask less than the default.",
esc.critical, defaults.critical
));
}
context::RiskLevel::Elevated if defaults.elevated.is_stricter_than(esc.elevated) => {
notes.push(format!(
"Note: context escalation for elevated contexts is set to {} (default {}).",
esc.elevated, defaults.elevated
));
}
_ => {}
}
DisplayContext {
command: None,
matched,
ignore_hint,
is_denied: !deny_reasons.is_empty(),
descriptions,
alternatives,
context_labels: context.labels.clone(),
effective_challenge: effective.challenge,
escalation_note: effective.note(),
severity_label,
blast_radius_label,
check_ids,
base_challenge: effective.base,
escalation_reasons: effective.reasons,
deny_reasons,
deny_hint,
notes,
}
}
#[must_use]
pub fn ignore_hint(checks: &[&Check], context: &RuntimeContext, denied: bool) -> Option<String> {
if denied
|| checks.is_empty()
|| checks.iter().any(|c| c.severity >= Severity::Critical)
|| context.risk_level == context::RiskLevel::Critical
|| context.is_root
{
return None;
}
let mut ids: Vec<&Check> = Vec::new();
for c in checks {
if !ids.iter().any(|x| x.id == c.id) {
ids.push(c);
}
}
let broad = |c: &&Check| {
matches!(
c.id.as_str(),
"fs-strict:any_deletion"
| "fs-strict:recursive_deletion"
| "fs-strict:folder_deletion"
| "fs-strict:change_permissions"
| "kubernetes-strict:delete_resource"
| "kubernetes-strict:update_resource"
)
};
ids.sort_by_key(|c| (broad(c), c.severity));
let cmds: Vec<String> = ids
.iter()
.map(|c| format!("shellfirm config ignore {}", c.id))
.collect();
let mut hint = format!(
"Not risky for you? Stop asking with `{}`.",
cmds.join(" && ")
);
let broad_ids: Vec<&str> = ids
.iter()
.filter(|c| broad(c))
.map(|c| c.id.as_str())
.collect();
if !broad_ids.is_empty() {
let _ = std::fmt::Write::write_fmt(
&mut hint,
format_args!(
" (`{}` is a broad catch-all: ignoring it silences it for every command it matches.)",
broad_ids.join("`, `")
),
);
}
Some(hint)
}
pub fn challenge_with_context(
settings: &Settings,
resolved: &ResolvedSettings,
checks: &[&Check],
context: &RuntimeContext,
merged_policy: &MergedPolicy,
prompter: &dyn Prompter,
blast_radii: &[(String, BlastRadiusInfo)],
) -> Result<ChallengeResult> {
let display = build_challenge_display(
settings,
resolved,
checks,
context,
merged_policy,
blast_radii,
);
Ok(prompter.run_challenge(&display))
}
#[must_use]
pub fn run_check_on_command<'a>(checks: &'a [Check], command: &str) -> Vec<&'a Check> {
run_check_on_command_with_env(checks, command, &crate::env::RealEnvironment)
}
#[must_use]
pub fn ignored_matches(settings: &Settings, command: &str, env: &dyn Environment) -> Vec<Check> {
let ignores = settings.effective_ignores();
if ignores.is_empty() {
return Vec::new();
}
let enabled: std::collections::HashSet<&str> =
settings.enabled_groups.iter().map(String::as_str).collect();
let switched_off: Vec<Check> = all_checks_cached()
.iter()
.filter(|c| ignores.contains(c.id.as_str()) && enabled.contains(c.from.as_str()))
.cloned()
.collect();
if switched_off.is_empty() {
return Vec::new();
}
let mut seen = std::collections::HashSet::new();
run_check_on_command_with_env(&switched_off, command, env)
.into_iter()
.filter(|c| seen.insert(c.id.clone()))
.cloned()
.collect()
}
#[must_use]
pub fn run_check_on_command_with_env<'a>(
checks: &'a [Check],
command: &str,
env: &dyn Environment,
) -> Vec<&'a Check> {
let mut parsed = crate::parser::parse(command);
let context_segments = line_context_segments(command, &parsed.segments);
parsed.segments.extend(context_segments);
let segment_matches: Vec<&Check> = parsed
.segments
.iter()
.flat_map(|s| match_segment(checks, s, &parsed.remote_segments, env))
.collect();
let flat_matches = if parsed.flat.is_empty() {
Vec::new()
} else {
match_flat(checks, &parsed.flat, env)
};
let mut seen = std::collections::HashSet::new();
segment_matches
.into_iter()
.chain(flat_matches)
.filter(|c| seen.insert(std::ptr::from_ref::<Check>(c)))
.collect()
}
#[must_use]
pub fn match_text<'a>(checks: &'a [Check], text: &str, env: &dyn Environment) -> Vec<&'a Check> {
match_text_impl(checks, text, env, false)
}
fn match_flat<'a>(checks: &'a [Check], flat: &str, env: &dyn Environment) -> Vec<&'a Check> {
match_text(checks, flat, env)
.into_iter()
.filter(|c| {
let re = c.test.as_str();
let pipeline = re
.match_indices("\\|")
.any(|(i, _)| !re[..i].ends_with('>'));
let path_check = c.filters.iter().any(|f| {
matches!(f, Filter::PathExists(_))
|| matches!(f, Filter::NotMatches(re) if re.starts_with('^'))
});
pipeline
|| (!path_check && c.test.find_iter(flat).any(|m| !spans_separator(m.as_str())))
})
.collect()
}
fn spans_separator(text: &str) -> bool {
text.split([' ', '\n'])
.any(|w| matches!(w, "&&" | "||" | ";" | "|" | "&" | "|&" | ";;"))
|| text.contains('\n')
}
fn match_segment<'a>(
checks: &'a [Check],
text: &str,
remote: &[String],
env: &dyn Environment,
) -> Vec<&'a Check> {
match_text_impl(checks, text, env, is_remote_text(remote, text))
}
fn is_remote_text(remote: &[String], text: &str) -> bool {
let found = |t: &str| remote.binary_search_by(|r| r.as_str().cmp(t)).is_ok();
found(text) || privileged_copy(text).is_some_and(found)
}
const LITERAL_INDEX_MIN_SEGMENTS: usize = 512;
struct LiteralIndex<'a> {
ac: aho_corasick::AhoCorasick,
literals: usize,
per_check: Vec<Option<Vec<usize>>>,
checks: &'a [Check],
}
impl<'a> LiteralIndex<'a> {
fn new(checks: &'a [Check]) -> Option<Self> {
let mut lits: Vec<&'static str> = Vec::new();
let mut ids: std::collections::HashMap<&'static str, usize> =
std::collections::HashMap::new();
let per_check = checks
.iter()
.map(|c| {
c.test.0.prefilter.map(|ls| {
ls.iter()
.map(|l| {
*ids.entry(l).or_insert_with(|| {
lits.push(l);
lits.len() - 1
})
})
.collect()
})
})
.collect();
let ac = aho_corasick::AhoCorasick::new(&lits).ok()?;
Some(Self {
ac,
literals: lits.len(),
per_check,
checks,
})
}
fn matches(
&self,
text: &str,
env: &dyn Environment,
assume_paths_exist: bool,
) -> Vec<&'a Check> {
let folded = crate::prefilter::fold(text);
let mut hit = vec![false; self.literals];
for m in self.ac.find_overlapping_iter(&folded) {
hit[m.pattern().as_usize()] = true;
}
self.checks
.iter()
.zip(&self.per_check)
.filter(|(c, lits)| {
if let Some(inner) = privileged_copy(text) {
return privileged_copy_matches(c, text, inner, env, assume_paths_exist);
}
lits.as_ref().is_none_or(|ids| ids.iter().any(|&i| hit[i]))
&& c.test.regex().is_match(text)
&& check_filters(c, text, env, assume_paths_exist)
})
.map(|(c, _)| c)
.collect()
}
}
fn privileged_copy(text: &str) -> Option<&str> {
text.strip_prefix(PRIVILEGED_MARKER)?.strip_prefix(' ')
}
fn privileged_copy_matches(
check: &Check,
text: &str,
inner: &str,
env: &dyn Environment,
assume_paths_exist: bool,
) -> bool {
if PRIVILEGE_SURVIVORS.contains(&check.id.as_str()) {
return false;
}
let names_copy = check.test.as_str().contains(PRIVILEGED_MARKER);
let anchored_exemption = check
.filters
.iter()
.any(|f| matches!(f, Filter::NotMatches(re) if re.starts_with('^')));
if !names_copy && !anchored_exemption {
return false;
}
let tested = if names_copy {
check.test.is_match(text)
} else {
check.test.is_match(text) || check.test.is_match(inner)
};
tested && check_filters(check, text, env, assume_paths_exist)
}
fn segment_matches_check(
check: &Check,
text: &str,
folded: &str,
env: &dyn Environment,
assume_paths_exist: bool,
) -> bool {
if let Some(inner) = privileged_copy(text) {
return privileged_copy_matches(check, text, inner, env, assume_paths_exist);
}
check.test.is_match_prefiltered(text, folded)
&& check_filters(check, text, env, assume_paths_exist)
}
fn match_text_impl<'a>(
checks: &'a [Check],
text: &str,
env: &dyn Environment,
assume_paths_exist: bool,
) -> Vec<&'a Check> {
let folded = crate::prefilter::fold(text);
checks
.iter()
.filter(|v| segment_matches_check(v, text, &folded, env, assume_paths_exist))
.collect()
}
#[cfg(test)]
fn check_custom_filter_with_env(check: &Check, command: &str, env: &dyn Environment) -> bool {
check_filters(check, command, env, false)
}
fn check_filters(
check: &Check,
command: &str,
env: &dyn Environment,
assume_paths_exist: bool,
) -> bool {
if check.filters.is_empty() {
return true;
}
let caps = check
.test
.captures(command)
.or_else(|| privileged_copy(command).and_then(|inner| check.test.captures(inner)));
for filter in &check.filters {
debug!("filter information: command {command:?} filter: {filter:?}");
let keep = match filter {
Filter::PathExists(group_idx) => {
let file_path = caps
.as_ref()
.and_then(|c| c.get(*group_idx))
.map_or_else(
|| {
warn!(
"check {:?}: PathExists references capture group {} which does not exist in regex",
check.id, group_idx
);
""
},
|m| m.as_str(),
);
if file_path.is_empty() {
false
} else if assume_paths_exist {
true
} else {
filter_path_exists_with_env(file_path, env)
}
}
Filter::NotContains(ref s) => !command.contains(s.as_str()),
Filter::Contains(ref s) => command.contains(s.as_str()),
Filter::NotMatches(ref re) => !filter_regex_matches(&check.id, re, command),
Filter::Matches(ref re) => filter_regex_matches(&check.id, re, command),
};
if !keep {
return false;
}
}
true
}
fn filter_regex_matches(check_id: &str, re: &str, command: &str) -> bool {
use std::collections::HashMap;
use std::sync::Mutex;
static CACHE: OnceLock<Mutex<HashMap<String, Option<Regex>>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let compiled = {
let mut guard = cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
guard
.entry(re.to_string())
.or_insert_with(|| match Regex::new(re) {
Ok(r) => Some(r),
Err(err) => {
warn!("check {check_id:?}: invalid filter regex {re:?}: {err}");
None
}
})
.clone()
};
compiled.is_some_and(|r| r.is_match(command))
}
fn filter_path_exists_with_env(file_path: &str, env: &dyn Environment) -> bool {
let cwd = std::cell::OnceCell::new();
let mut tokens = file_path.split_whitespace();
while let Some(tok) = tokens.next() {
let bare = tok.trim_start_matches(|c: char| c.is_ascii_digit());
if bare.starts_with('>') || bare.starts_with('<') || bare.starts_with("&>") {
tokens.next(); continue;
}
if tok.starts_with('-') && tok != "-" {
continue;
}
if single_path_exists(&crate::parser::desentinel(tok), env, &cwd) {
return true;
}
}
false
}
fn single_path_exists(
file_path: &str,
env: &dyn Environment,
cwd: &std::cell::OnceCell<Option<std::path::PathBuf>>,
) -> bool {
use std::borrow::Cow;
let trimmed = file_path.trim();
let home_prefix = ["~", "$HOME", "${HOME}"]
.into_iter()
.find(|p| trimmed == *p || trimmed.starts_with(&format!("{p}/")));
let file_path: Cow<'_, str> = if let Some(prefix) = home_prefix {
match env.home_dir() {
Some(home) => Cow::Owned(trimmed.replacen(prefix, &home.display().to_string(), 1)),
None => return true,
}
} else if let Some(user_path) = expand_user_tilde(trimmed) {
Cow::Owned(user_path)
} else {
Cow::Borrowed(trimmed)
};
if [
"$RANDOM",
"${RANDOM}",
"$$",
"${$}",
"$(date",
"`date",
"$(uuidgen",
"$(mktemp",
]
.iter()
.any(|m| file_path.contains(m))
{
return false;
}
if file_path.contains(['*', '?', '$']) {
return true;
}
if file_path.contains('[') && file_path.contains(']') {
return bracket_candidates(&file_path).is_none_or(|cands| {
cands
.iter()
.any(|c| single_path_exists(c, env, cwd) && !c.contains('['))
});
}
let Some(base) = cwd.get_or_init(|| env.current_dir().ok()) else {
debug!("could not get current dir");
return true;
};
let full_path = base.join(&*file_path);
debug!("check if {} path exists", full_path.display());
env.path_exists(&full_path)
}
pub(crate) fn max_challenge(a: Challenge, b: Challenge) -> Challenge {
a.stricter(b)
}
fn dedup_check_matches<'a>(primary: Vec<&'a Check>, secondary: Vec<&'a Check>) -> Vec<&'a Check> {
let mut seen_ids = std::collections::HashSet::new();
let mut result = Vec::with_capacity(primary.len() + secondary.len());
for m in primary.into_iter().chain(secondary) {
if seen_ids.insert(m.id.as_str()) {
result.push(m);
}
}
result
}
#[derive(Debug, Clone)]
pub struct PipelineResult {
pub stripped_command: String,
pub command_parts: Vec<String>,
pub active_matches: Vec<Check>,
pub skipped_matches: Vec<Check>,
pub context: RuntimeContext,
pub relevant_context: RuntimeContext,
pub max_severity: Severity,
pub is_denied: bool,
pub alternatives: Vec<AlternativeInfo>,
pub merged_policy: MergedPolicy,
pub blast_radii: Vec<(String, BlastRadiusInfo)>,
pub max_blast_scope: Option<BlastScope>,
pub skipped_missing_paths: Vec<(String, String)>,
}
const MAX_EXPLAINED_SEGMENT: usize = 4096;
fn missing_path_skips(
checks: &[Check],
segments: &[String],
remote: &[String],
env: &dyn Environment,
matched: &[&Check],
) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = Vec::new();
for seg in segments {
if seg.len() > MAX_EXPLAINED_SEGMENT
|| remote.binary_search(seg).is_ok()
|| !seg
.split(' ')
.next()
.is_some_and(|p| RESOLVED_PROGRAMS.contains(&p))
{
continue;
}
for c in match_text_impl(checks, seg, env, true) {
let Some(group) = c.filters.iter().find_map(|f| match f {
Filter::PathExists(g) => Some(*g),
_ => None,
}) else {
continue;
};
if matched.iter().any(|m| m.id == c.id) || check_filters(c, seg, env, false) {
continue;
}
let captured = c
.test
.captures(seg)
.and_then(|caps| caps.get(group).map(|m| m.as_str().to_string()))
.unwrap_or_default();
let cwd = std::cell::OnceCell::new();
let mut tokens = captured.split_whitespace();
while let Some(tok) = tokens.next() {
if crate::parser::is_redirect_word(tok) {
tokens.next();
continue;
}
if tok.starts_with('-') || tok.contains("{}") {
continue;
}
let path = crate::parser::desentinel(tok);
if single_path_exists(&path, env, &cwd)
|| out.iter().any(|(id, p)| *id == c.id && *p == path)
{
continue;
}
out.push((c.id.clone(), path));
}
}
}
out
}
#[allow(clippy::too_many_lines)]
pub fn analyze_command(
command: &str,
settings: &Settings,
resolved: &ResolvedSettings,
checks: &[Check],
env: &dyn Environment,
strip_quotes_re: &Regex,
) -> Result<PipelineResult> {
let _ = strip_quotes_re;
let mut parsed = crate::parser::parse(command);
let context_segments = line_context_segments(command, &parsed.segments);
parsed.segments.extend(context_segments);
let sensitive_hits =
context::sensitive_path_hits(env, &settings.context.sensitive_paths, &parsed);
for hit in &sensitive_hits {
parsed
.segments
.push(format!("{SENSITIVE_PATH_MARKER} {hit}"));
}
spell_own_user(env, &mut parsed.segments);
spell_parent_paths_in_repo(env, &mut parsed.segments);
spell_linked_operands(env, command, &mut parsed.segments);
let glob_segments = glob_resolved_segments(env, &parsed);
parsed.segments.extend(glob_segments);
let resolved_segments = cwd_resolved_segments(env, &parsed, command);
parsed.segments.extend(resolved_segments);
let created_segments = created_path_segments(env, &parsed);
parsed.segments.extend(created_segments);
let cwd = env.current_dir().unwrap_or_default();
let target_dirs = context::command_target_dirs(command);
let discovery = policy::discover_for(env, &cwd, &target_dirs);
policy::warn_policy_problems(&discovery);
let project_policy = discovery.policy;
let stop_at_critical = settings.deny_patterns_ids.is_empty()
&& project_policy
.as_ref()
.is_none_or(|p| p.checks.is_empty() && p.deny.is_empty());
let sql_files = sql_file_segments(env, command, &parsed, stop_at_critical.then_some(checks));
let sql_client = line_sql_client(&parsed);
parsed.segments.extend(sql_files.segments.iter().cloned());
if let Some(branch) =
context::protected_force_with_lease(env, &settings.context, command, &parsed)
{
parsed
.segments
.push(if branch == context::UNKNOWN_PUSH_TARGET {
UNKNOWN_TARGET_FORCE_PUSH_MARKER.to_string()
} else {
format!("{PROTECTED_FORCE_PUSH_MARKER} {branch}")
});
}
let empty_var = empty_variable_segments(env, &parsed);
parsed.segments.extend(empty_var);
for repo in repositories_moved_away(env, &parsed) {
parsed
.segments
.push(format!("{REPOSITORY_DELETE_MARKER} {repo}"));
}
for repo in deleted_repositories(env, &parsed) {
parsed
.segments
.push(if repo.starts_with(GIT_DIR_DELETE_MARKER) {
repo
} else {
format!("{REPOSITORY_DELETE_MARKER} {repo}")
});
}
let stripped = command.to_string();
let parsed_for_work = crate::parser::Parsed {
segments: parsed.segments.clone(),
remote_segments: parsed.remote_segments.clone(),
..crate::parser::Parsed::default()
};
let work = if parsed_for_work
.segments
.iter()
.any(|s| !deleted_folder_operands(s).is_empty())
{
folders_with_uncommitted_work(env, &parsed_for_work)
} else {
WorkFolders::default()
};
for seg in &parsed_for_work.segments {
if !seg.starts_with("mv ") {
continue;
}
for op in deleted_folder_operands(seg) {
if work.dirty.contains(&op) || work.unknown.contains(&op) {
parsed
.segments
.push(format!("{WORK_MOVED_AWAY_MARKER} {op}"));
}
}
}
let command_parts = parsed.segments;
let remote_parts = parsed.remote_segments;
let flat = parsed.flat;
debug!("analyze_command: parts={command_parts:?}");
let index = (command_parts.len() > LITERAL_INDEX_MIN_SEGMENTS)
.then(|| LiteralIndex::new(checks))
.flatten();
let segment_matches: Vec<&Check> = command_parts
.iter()
.flat_map(|c| {
index.as_ref().map_or_else(
|| match_segment(checks, c, &remote_parts, env),
|ix| ix.matches(c, env, is_remote_text(&remote_parts, c)),
)
})
.collect();
let matches = if flat.is_empty() {
segment_matches
} else {
let full_matches = match_flat(checks, &flat, env);
dedup_check_matches(segment_matches, full_matches)
};
let mut matches = matches;
let unread_source = || {
checks
.iter()
.find(|c| c.id == "database:sql_from_file")
.is_some_and(|c| {
command_parts.iter().any(|s| {
!s.starts_with("shellfirm-")
&& !sql_files.consumed.contains(s)
&& segment_matches_check(c, s, &crate::prefilter::fold(s), env, true)
})
})
};
if sql_files.referenced && sql_files.all_read && !unread_source() {
matches.retain(|c| c.id != "database:sql_from_file");
}
debug!("analyze_command: {} matches found", matches.len());
let policy_has_extra_checks = project_policy
.as_ref()
.is_some_and(|pp| !pp.checks.is_empty());
if matches.is_empty() && !policy_has_extra_checks {
debug!("analyze_command: no matches and no policy checks, skipping context detection");
let skipped_missing_paths =
missing_path_skips(checks, &command_parts, &remote_parts, env, &[]);
return Ok(PipelineResult {
skipped_missing_paths,
stripped_command: stripped,
command_parts,
active_matches: Vec::new(),
skipped_matches: Vec::new(),
context: RuntimeContext::default(),
relevant_context: RuntimeContext::default(),
max_severity: Severity::default(),
is_denied: false,
alternatives: Vec::new(),
merged_policy: MergedPolicy::default(),
blast_radii: Vec::new(),
max_blast_scope: None,
});
}
let target_policy_context = (!target_dirs.is_empty())
.then(|| project_policy.as_ref().and_then(|p| p.context.clone()))
.flatten();
let mut context_config = settings.context.clone();
if let Some(pc) = &target_policy_context {
let _ = pc.apply_to(&mut context_config);
}
let command_contexts = context::command_contexts(env, &context_config, command);
let runtime_context = command_contexts.full(&context_config);
let mut merged_policy = if let Some(ref pp) = project_policy {
policy::merge_into_settings(settings, pp, runtime_context.git_branch.as_deref())
} else {
MergedPolicy::default()
};
let mut all_matches: Vec<&Check> = matches;
if !merged_policy.extra_checks.is_empty() {
let extra_segment: Vec<&Check> = command_parts
.iter()
.flat_map(|c| match_segment(&merged_policy.extra_checks, c, &remote_parts, env))
.collect();
let extra = if flat.is_empty() {
extra_segment
} else {
let extra_full = match_flat(&merged_policy.extra_checks, &flat, env);
dedup_check_matches(extra_segment, extra_full)
};
all_matches.extend(extra);
}
let all_matches: Vec<Check> = raise_for_uncommitted_work(&work, &command_parts, all_matches);
let mut all_matches =
drop_restores_of_clean_paths(env, &command_parts, &remote_parts, all_matches);
for c in &mut all_matches {
if c.id == "database:sql_from_file" {
c.description = sql_files.sql_from_file_description(&c.description, sql_client);
}
}
let (active_matches, skipped_matches): (Vec<Check>, Vec<Check>) = if let Some(min_sev) =
resolved.min_severity
{
all_matches.into_iter().partition(|c| {
c.severity >= min_sev || merged_policy.is_enforced(&c.id) || !sensitive_hits.is_empty()
})
} else {
(all_matches, Vec::new())
};
let max_severity = active_matches
.iter()
.chain(skipped_matches.iter())
.map(|c| c.severity)
.max()
.unwrap_or_default();
let is_denied = active_matches
.iter()
.any(|c| settings.deny_patterns_ids.contains(&c.id) || merged_policy.is_denied(&c.id));
let mut alternatives = Vec::new();
for check in &active_matches {
if let Some(ref alt) = check.alternative {
let matching: Vec<&String> = command_parts
.iter()
.filter(|s| check.test.is_match(s))
.collect();
let is_remote = |s: &&String| remote_parts.binary_search(s).is_ok();
if check.from.starts_with("fs")
&& !matching.is_empty()
&& matching.iter().all(is_remote)
{
continue;
}
let segment = matching
.iter()
.find(|s| !is_remote(s))
.or_else(|| matching.first())
.map_or(stripped.as_str(), |s| s.as_str());
let alt = fill_alternative(alt, segment);
let already_has = alternatives
.iter()
.any(|a: &AlternativeInfo| a.suggestion == alt);
if !already_has {
alternatives.push(AlternativeInfo {
suggestion: alt,
explanation: check.alternative_info.clone(),
});
}
}
}
let blast_radii = if settings.blast_radius {
let unredirected = |segs: &[String]| -> Vec<String> {
segs.iter()
.map(|s| {
if s.starts_with("git ") || s.starts_with("kubectl ") {
crate::parser::without_redirects(s)
} else {
s.clone()
}
})
.collect()
};
let br_parts = unredirected(&command_parts);
let mut br_remote = unredirected(&remote_parts);
br_remote.sort();
blast_radius::compute_for_matches_remote_aware(
&active_matches,
&br_parts,
&br_remote,
&stripped,
env,
)
} else {
Vec::new()
};
let mut blast_radii = blast_radii;
if settings.blast_radius && !sql_files.origins.is_empty() {
for c in &active_matches {
if blast_radii.iter().any(|(id, _)| *id == c.id) {
continue;
}
let hit = sql_files.origins.iter().find(|(seg, _)| {
!match_segment(std::slice::from_ref(c), seg, &remote_parts, env).is_empty()
});
if let Some((seg, file)) = hit {
let mut stmt = crate::parser::desentinel(seg).trim().to_string();
if stmt.chars().count() > 60 {
stmt = format!("{}…", stmt.chars().take(59).collect::<String>());
}
let stopped = if sql_files.stopped_at_critical && c.severity == Severity::Critical {
" (scan stopped at the first Critical statement)"
} else {
""
};
blast_radii.push((
c.id.clone(),
BlastRadiusInfo {
scope: BlastScope::Project,
description: format!("`{stmt}` in {file}{stopped}"),
},
));
}
}
}
let max_blast_scope = blast_radii.iter().map(|(_, br)| br.scope).max();
let matched_groups: std::collections::HashSet<&str> =
active_matches.iter().map(|c| c.from.as_str()).collect();
let groups_of = |text: &str| -> std::collections::HashSet<String> {
let mut segments = crate::parser::parse(text).segments;
let copies = privileged_copies(text, &segments);
segments.extend(copies);
active_matches
.iter()
.filter(|c| {
segments.iter().any(|s| {
let folded = crate::prefilter::fold(s);
segment_matches_check(c, s, &folded, env, true)
})
})
.map(|c| c.from.clone())
.collect()
};
let relevant_context = command_contexts.relevant(&context_config, &groups_of, &matched_groups);
let target_floor = target_policy_context
.as_ref()
.and(match relevant_context.risk_level {
context::RiskLevel::Critical => Some(context_config.escalation.critical),
context::RiskLevel::Elevated => Some(context_config.escalation.elevated),
context::RiskLevel::Normal => None,
});
if let Some(floor) = target_floor {
for c in &active_matches {
let e = merged_policy
.challenge_overrides
.entry(c.id.clone())
.or_insert(floor);
*e = e.stricter(floor);
}
}
let matched_refs: Vec<&Check> = active_matches.iter().chain(&skipped_matches).collect();
let skipped_missing_paths =
missing_path_skips(checks, &command_parts, &remote_parts, env, &matched_refs);
Ok(PipelineResult {
skipped_missing_paths,
stripped_command: stripped,
command_parts,
active_matches,
skipped_matches,
context: runtime_context,
relevant_context,
max_severity,
is_denied,
alternatives,
merged_policy,
blast_radii,
max_blast_scope,
})
}
#[must_use]
pub fn fill_alternative(alt: &str, segment: &str) -> String {
if !alt.contains('<') {
return alt.to_string();
}
let owned: Vec<String> = segment
.split_whitespace()
.map(crate::parser::desentinel)
.collect();
let words: Vec<&str> = owned.iter().map(String::as_str).collect();
let prog = words.first().copied().unwrap_or("");
let operands: Vec<&str> = words
.iter()
.skip(1)
.take_while(|w| !crate::parser::is_redirect_word(w))
.filter(|w| !w.starts_with('-'))
.copied()
.collect();
let after = |keys: &[&str]| -> Option<&str> {
words
.iter()
.position(|w| keys.contains(w))
.and_then(|i| words.get(i + 1))
.filter(|w| !w.starts_with('-'))
.copied()
};
let path = match prog {
"rm"
| "rmdir"
| "shred"
| "unlink"
| "srm"
| REPOSITORY_DELETE_MARKER
| GIT_DIR_DELETE_MARKER
| WORK_MOVED_AWAY_MARKER
if !operands.is_empty() =>
{
Some(
operands
.iter()
.map(|o| quote_for_display(o))
.collect::<Vec<_>>()
.join(" "),
)
}
_ => None,
};
let branch = if prog == "git" {
after(&["-D", "-d", "--delete", "-f", "--force"])
.or_else(|| operands.iter().skip(1).find(|w| **w != ".").copied())
.map(str::to_string)
} else {
None
};
let namespace =
after(&["ns", "namespace", "namespaces", "-n", "--namespace"]).map(str::to_string);
let url = words
.iter()
.find(|w| w.starts_with("http://") || w.starts_with("https://"))
.map(|w| (*w).to_string());
let bucket = words.iter().find_map(|w| {
w.strip_prefix("s3://")
.or_else(|| w.strip_prefix("gs://"))
.map(|b| {
b.trim_end_matches('/')
.split('/')
.next()
.unwrap_or(b)
.to_string()
})
});
let mut out = alt.to_string();
for (ph, val) in [
("<path>", &path),
("<file>", &path),
("<branch>", &branch),
("<namespace>", &namespace),
("<url>", &url),
("<bucket>", &bucket),
] {
if let Some(v) = val {
if !v.is_empty() {
out = out.replace(ph, &crate::context::escape_invisible(v));
}
}
}
out
}
fn quote_for_display(s: &str) -> String {
if s.chars()
.any(|c| c.is_whitespace() || matches!(c, '\'' | '"' | '\\' | ';' | '&' | '|'))
{
format!("'{}'", s.replace('\'', "'\\''"))
} else {
s.to_string()
}
}
#[must_use]
pub fn split_command(command: &str) -> Vec<String> {
let mut parts = Vec::new();
let bytes = command.as_bytes();
let len = bytes.len();
let mut i = 0;
let mut start = i;
let mut in_single_quote = false;
let mut in_double_quote = false;
while i < len {
let b = bytes[i];
if b == b'\'' && !in_double_quote {
in_single_quote = !in_single_quote;
i += 1;
} else if b == b'"' && !in_single_quote {
in_double_quote = !in_double_quote;
i += 1;
} else if !in_single_quote && !in_double_quote {
let (is_split, advance) = if i + 1 < len
&& ((b == b'&' && bytes[i + 1] == b'&') || (b == b'|' && bytes[i + 1] == b'|'))
{
(true, 2)
} else if b == b'|' || b == b';' {
(true, 1)
} else {
(false, 1)
};
if is_split {
parts.push(command[start..i].to_string());
i += advance;
start = i;
} else {
i += 1;
}
} else {
i += 1;
}
}
if start < len {
parts.push(command[start..].to_string());
}
parts
}
#[cfg(test)]
pub(crate) fn fixture_files() -> Vec<(std::path::PathBuf, String)> {
let mut out = Vec::new();
for entry in std::fs::read_dir("tests/checks").expect("tests/checks") {
let path = entry.expect("tests/checks entry").path();
let hidden = path
.file_name()
.and_then(|n| n.to_str())
.is_none_or(|n| n.starts_with('.'));
if hidden || !path.extension().is_some_and(|e| e == "yaml") {
continue;
}
let text =
std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
out.push((path, text));
}
out.sort();
out
}
#[cfg(test)]
mod test_checks {
use insta::{assert_debug_snapshot, with_settings};
use super::*;
#[test]
fn challenge_with_context_uses_resolved_settings_for_shell() {
use crate::config::{InheritOr, Mode, Settings};
let mut settings = Settings::default();
settings.challenge = Challenge::Math;
settings.agent.challenge = InheritOr::Set(Challenge::Yes); let resolved = settings.resolved_for(Mode::Shell);
assert_eq!(resolved.challenge, Challenge::Math);
}
const CHECKS: &str = r###"
- from: test-1
test: test-(1)
enable: true
description: ""
id: ""
- from: test-2
test: test-(1|2)
enable: true
description: ""
id: ""
- from: test-disabled
test: test-disabled
enable: true
description: ""
id: ""
"###;
#[test]
fn can_run_check_on_command() {
let checks: Vec<Check> = serde_yaml::from_str(CHECKS).unwrap();
with_settings!({filters => vec![
(r#"(?s)test:\s*Regex\(\s*"([^"]+)",?\s*\)"#, "test: $1"),
]}, {
assert_debug_snapshot!(run_check_on_command(&checks, "test-1"));
assert_debug_snapshot!(run_check_on_command(&checks, "unknown command"));
});
}
#[test]
fn can_check_custom_filter_with_file_exists() {
use std::collections::HashSet;
let filters = vec![Filter::PathExists(1)];
let check = Check {
id: "id".to_string(),
test: Regex::new("(?:^|[^>])>([^>].*)").unwrap().into(),
description: "some description".to_string(),
from: "test".to_string(),
challenge: Challenge::default(),
filters,
alternative: None,
alternative_info: None,
severity: Severity::default(),
};
let env_no_file = crate::env::MockEnvironment {
cwd: "/mock".into(),
..Default::default()
};
let command = "cat 'write message' > /mock/app/message.txt";
assert_debug_snapshot!(check_custom_filter_with_env(&check, command, &env_no_file));
let mut existing = HashSet::new();
existing.insert(std::path::PathBuf::from("/mock/app/message.txt"));
let env_with_file = crate::env::MockEnvironment {
cwd: "/mock".into(),
existing_paths: existing,
..Default::default()
};
assert_debug_snapshot!(check_custom_filter_with_env(
&check,
command,
&env_with_file
));
}
#[test]
fn can_check_custom_filter_with_str_contains() {
let filters = vec![Filter::NotContains("--dry-run".to_string())];
let check = Check {
id: "id".to_string(),
test: Regex::new("(delete)").unwrap().into(),
description: "some description".to_string(),
from: "test".to_string(),
challenge: Challenge::default(),
filters,
alternative: None,
alternative_info: None,
severity: Severity::default(),
};
let env = crate::env::MockEnvironment::default();
assert_debug_snapshot!(check_custom_filter_with_env(&check, "delete", &env));
assert_debug_snapshot!(check_custom_filter_with_env(
&check,
"delete --dry-run",
&env
));
}
#[test]
fn can_check_custom_filter_with_contains() {
let filters = vec![Filter::Contains("--force".to_string())];
let check = Check {
id: "id".to_string(),
test: Regex::new("(push)").unwrap().into(),
description: "some description".to_string(),
from: "test".to_string(),
challenge: Challenge::default(),
filters,
alternative: None,
alternative_info: None,
severity: Severity::default(),
};
let env = crate::env::MockEnvironment::default();
assert!(!check_custom_filter_with_env(
&check,
"git push origin main",
&env
));
assert!(check_custom_filter_with_env(
&check,
"git push --force origin main",
&env
));
}
#[test]
fn a_dry_run_exemption_lets_the_last_value_win() {
let mut checked = 0;
for check in all_checks_cached() {
for filter in &check.filters {
let Filter::NotMatches(re) = filter else {
continue;
};
let re = Regex::new(re).unwrap();
for word in ["--dry-run", "-dry-run", "--dryrun", "--dryRun"] {
if !re.as_str().contains(&word[word.len() - 7..]) {
continue;
}
checked += 1;
let name = word.trim_start_matches('-');
for later in [
format!("{word}=false"),
format!("{word}=none"),
format!("--no-{name}"),
] {
for first in [word.to_string(), format!("{word}=true")] {
let text = format!("x {first} {later} y");
assert!(
!re.is_match(&text),
"{}: the exemption skips {text:?}",
check.id
);
}
}
}
}
}
assert!(checked >= 20, "only {checked} dry-run exemptions found");
}
#[test]
fn a_dry_run_word_after_an_option_that_takes_a_value_is_not_a_dry_run() {
let mut checked = 0;
for check in all_checks_cached() {
for filter in &check.filters {
let Filter::NotMatches(re) = filter else {
continue;
};
let re = Regex::new(re).unwrap();
for word in ["--dry-run", "-dry-run", "--dryrun", "--dryRun"] {
if !re.as_str().contains(&word[word.len() - 7..]) {
continue;
}
checked += 1;
for text in [
format!("x y --timeout {word}"),
format!("x y -l {word}"),
format!("x y --context {word} z"),
format!("x y '{word}'"),
] {
assert!(
!re.is_match(&text),
"{}: the exemption skips {text:?}",
check.id
);
}
}
}
}
assert!(checked >= 20, "only {checked} dry-run exemptions found");
}
#[test]
fn quoted_dry_run_words_are_found_at_any_depth() {
let found = |c: &str| {
let mut out = Vec::new();
quoted_dry_run_words(c, 0, &mut out);
out
};
assert_eq!(
found("kubectl drain n '--dry-run=client'"),
["--dry-run=client"]
);
assert_eq!(found("npm unpublish p \"--dry-run\""), ["--dry-run"]);
assert_eq!(found("mongorestore --drop \\--dryRun d"), ["--dryRun"]);
assert_eq!(found("helm uninstall w $'--dry-run'"), ["--dry-run"]);
assert_eq!(
found("bash -c \"kubectl drain n '--dry-run=client'\""),
["--dry-run=client"]
);
assert!(found("kubectl drain n --dry-run=client").is_empty());
assert!(found("bash -c \"kubectl drain n --dry-run=client\"").is_empty());
assert!(found("git commit -m 'dry run notes'").is_empty());
assert_eq!(found("velero restore create r '-o' yaml"), ["-o"]);
}
#[test]
fn submodule_update_init_is_line_checked() {
let extra = |c: &str| line_context_segments(c, &crate::parser::parse(c).segments);
for flagged in [
"git -c submodule.lib.update='!rm -rf ~' submodule update --init",
"git -C vendor submodule update --init",
"GIT_CONFIG_COUNT=1 git submodule update --init",
"git config submodule.lib.update '!rm -rf ~' && git submodule update --init",
"git submodule update --init | sh",
"git submodule update --init 2>&1 | tail -5",
"./setup.sh; git submodule update --init",
"git pull --upload-pack 'rm -rf ~' && git submodule update --init",
"git clone --template=/tmp/t ~/r.git w && cd w && git submodule update --init",
"git config x y & git submodule update --init",
"git pull && HOME=/tmp/evil git submodule update --init",
"git submodule update --init && git config x y && git submodule update --init",
"git fetch origin +main:main && git submodule update --init",
"git pull origin +main:main && git submodule update --init",
"git fetch origin '+refs/*:refs/*' && git submodule update --init",
"git fetch . +HEAD~5:main && git submodule update --init",
"git fetch --prune origin '+refs/tags/*:refs/tags/*' && git submodule update --init",
"git fetch origin main:main && git submodule update --init",
"git fetch origin refs/heads/main:refs/heads/main && git submodule update --init",
"git fetch origin +main && git submodule update --init",
"git fetch origin ^main && git submodule update --init",
"git fetch 'ext::sh -c touch% /tmp/pwn' main && git submodule update --init",
] {
assert!(
extra(flagged)
.iter()
.any(|s| s.starts_with(LINE_CONTEXT_MARKER)),
"{flagged}"
);
}
for clean in [
"git submodule update --init",
"cd vendor && git submodule update --init --recursive",
"git submodule update --init && git status > /dev/null",
"git submodule update --init; ./setup.sh",
"git pull --ff-only origin main && git submodule update --init",
"git fetch -p && git checkout -q v1.2 && git submodule update --init",
"git switch -c fix main && git submodule update --init",
"git clone -q --depth 1 ~/r.git w && cd w && git submodule update --init",
"git fetch origin main && git submodule update --init",
"git pull --ff-only origin feature/login && git submodule update --init",
"git fetch ../other.git main && git submodule update --init",
"git fetch https://example.com/r.git v1.2 && git submodule update --init",
] {
assert!(extra(clean).is_empty(), "{clean}: {:?}", extra(clean));
}
}
fn privileged(cmd: &str) -> Vec<String> {
line_context_segments(cmd, &crate::parser::parse(cmd).segments)
.into_iter()
.filter_map(|s| privileged_copy(&s).map(crate::parser::desentinel))
.collect()
}
#[test]
fn privilege_is_decided_per_segment_from_command_position() {
for (cmd, seg) in [
("sudo rm -rf node_modules", "rm -rf node_modules"),
("sudo -u root rm -rf node_modules", "rm -rf node_modules"),
("sudo -k rm -rf node_modules", "rm -rf node_modules"),
("doas rm -rf node_modules", "rm -rf node_modules"),
("su -c 'rm -rf node_modules'", "rm -rf node_modules"),
("pkexec rm -rf node_modules", "rm -rf node_modules"),
("run0 rm -rf node_modules", "rm -rf node_modules"),
(
"runuser -u root -- rm -rf node_modules",
"rm -rf node_modules",
),
("env sudo rm -rf node_modules", "rm -rf node_modules"),
("timeout 60 sudo rm -rf node_modules", "rm -rf node_modules"),
("FOO=1 sudo rm -rf node_modules", "rm -rf node_modules"),
("sh -c 'sudo rm -rf node_modules'", "rm -rf node_modules"),
(
"bash -c \"sudo rm -rf node_modules\"",
"rm -rf node_modules",
),
("cd apps/web && sudo rm -rf .next", "rm -rf apps/web/.next"),
("/usr/bin/sudo rm -rf node_modules", "rm -rf node_modules"),
("'su''do' rm -rf node_modules", "rm -rf node_modules"),
("s\\udo rm -rf node_modules", "rm -rf node_modules"),
("echo x | (sudo rm -rf node_modules)", "rm -rf node_modules"),
(
"if true; then sudo rm -rf node_modules; fi",
"rm -rf node_modules",
),
("{ sudo rm -rf node_modules; }", "rm -rf node_modules"),
("alias s=sudo; s rm -rf node_modules", "rm -rf node_modules"),
(
"SUDO=sudo; $SUDO rm -rf node_modules",
"rm -rf node_modules",
),
(
"\"${SUDO:-sudo}\" rm -rf node_modules",
"rm -rf node_modules",
),
("${SUDO:-sudo} rm -rf node_modules", "rm -rf node_modules"),
(
"S() { sudo \"$@\"; }; S rm -rf node_modules",
"rm -rf node_modules",
),
(
"$(command -v sudo) rm -rf node_modules",
"rm -rf node_modules",
),
(
"cmd=(sudo rm); \"${cmd[@]}\" -rf node_modules",
"rm -rf node_modules",
),
("chroot / rm -rf node_modules", "rm -rf node_modules"),
(
"setpriv --reuid=0 --regid=0 --init-groups rm -rf node_modules",
"rm -rf node_modules",
),
(
"systemd-run --uid=0 --pty rm -rf node_modules",
"rm -rf node_modules",
),
("nsenter -t 1 -a rm -rf node_modules", "rm -rf node_modules"),
("chroot / npx rimraf node_modules", "rm -rf node_modules"),
("env -S 'rm -rf node_modules'", "rm -rf node_modules"),
("flock /tmp/l rm -rf node_modules", "rm -rf node_modules"),
("xargs rm -rf node_modules", "rm -rf node_modules"),
(
"find . -maxdepth 0 -exec sudo rm -rf node_modules \\;",
"rm -rf node_modules",
),
(
"S=sudo; bash -c \"$S rm -rf node_modules\"",
"rm -rf node_modules",
),
(
"rm -rf \"$(sudo rm -rf node_modules)\"",
"rm -rf node_modules",
),
(
"X=$(sudo rm -rf node_modules) rm -rf node_modules",
"rm -rf node_modules",
),
(
"please git merge --no-ff feature/login",
"git merge --no-ff feature/login",
),
("gosu root git cherry-pick abc123", "git cherry-pick abc123"),
(
"docker run --rm -v \"$PWD\":/w -w /w alpine git stash pop",
"git stash pop",
),
(
"\"$1\" git worktree add ../wt main",
"git worktree add ../wt main",
),
(
"rm() { sudo command rm \"$@\"; }; rm -rf node_modules",
"rm -rf node_modules",
),
(
"ssh root@localhost 'rm -rf node_modules'",
"rm -rf node_modules",
),
("ssh bastion rm -rf node_modules", "rm -rf node_modules"),
("docker exec web rm -rf node_modules", "rm -rf node_modules"),
(
"kubectl exec web -- rm -rf node_modules",
"rm -rf node_modules",
),
(
"sudo -s <<'EOF'\nrm -rf node_modules\nEOF",
"rm -rf node_modules",
),
(
"sudo -i <<'EOF'\nrm -rf node_modules\nEOF",
"rm -rf node_modules",
),
(
"doas -s <<'EOF'\nrm -rf node_modules\nEOF",
"rm -rf node_modules",
),
("sudo -s <<< 'rm -rf node_modules'", "rm -rf node_modules"),
(
"sudo su - <<'EOF'\nrm -rf node_modules\nEOF",
"rm -rf node_modules",
),
(
"sudo -iu root <<'EOF'\nrm -rf node_modules\nEOF",
"rm -rf node_modules",
),
(
"cat <<'EOF' | sudo -s\nrm -rf node_modules\nEOF",
"rm -rf node_modules",
),
("sudo -k; sudo rm -rf node_modules", "rm -rf node_modules"),
(
"git commit -m x && sudo rm -rf node_modules",
"rm -rf node_modules",
),
(
"# no sudo here\nsudo rm -rf node_modules",
"rm -rf node_modules",
),
] {
assert!(
privileged(cmd)
.iter()
.any(|s| s == seg || s.starts_with(&format!("{seg} "))),
"{cmd}: {:?}",
privileged(cmd)
);
}
for cmd in [
"rm -rf node_modules",
"env rm -rf node_modules",
"env -i PATH=/usr/bin rm -rf node_modules",
"env -u HOME rm -rf node_modules",
"timeout 60 rm -rf node_modules",
"timeout -s KILL -k 5 --foreground 60 rm -rf node_modules",
"nice rm -rf node_modules",
"nice -n 10 rm -rf node_modules",
"nohup rm -rf node_modules",
"time rm -rf node_modules",
"time -p rm -rf node_modules",
"command rm -rf node_modules",
"exec rm -rf node_modules",
"stdbuf -oL rm -rf node_modules",
"ionice -c 3 rm -rf node_modules",
"nice -n 5 timeout 60 env FOO=1 rm -rf node_modules",
"FOO=1 rm -rf node_modules",
"sh -c 'rm -rf node_modules'",
"npx rimraf node_modules",
"! rm -rf node_modules",
"(rm -rf node_modules)",
"{ rm -rf node_modules; }",
"if true; then rm -rf node_modules; fi",
"cd apps/web && rm -rf .next",
"# project-local deps, no sudo needed\nrm -rf node_modules",
"rm -rf node_modules # sudo not needed",
"echo 'tip: no sudo needed' && rm -rf node_modules",
"git commit -m 'docs: sudo is not needed' && rm -rf node_modules",
"gh pr create -t 'docs: drop sudo' -b 'no sudo' && rm -rf node_modules",
"grep -rn sudo docs/ | head; rm -rf node_modules",
"rm -rf node_modules # doas",
"git cherry-pick abc123 # sudo",
"git commit -m 'docs: sudo' && git merge --no-ff docs/sudo",
"cat > docs/x.md <<'EOF'\nsudo rm -rf node_modules\nEOF\nrm -rf node_modules",
"printf '%s\\n' 'run: sudo make install' >> docs/install.md && rm -rf node_modules",
"rg -n 'sudo ' scripts/ ; chmod 600 .env",
"echo \"use doas on openbsd\" > NOTES.md; rm -f yarn.lock",
"git commit -m \"$(cat <<'EOF'\ndocs: explain sudo usage\nEOF\n)\" && rm -rf node_modules",
"sudo -k; rm -rf node_modules",
"sudo --version; rm -rf node_modules",
"sudo cd . && rm -rf node_modules",
"nice timeout 60 git cherry-pick abc123",
"env -i PATH=/usr/bin git stash pop",
"for b in a b; do git merge --no-ff $b; done",
] {
let p = privileged(cmd);
assert!(
!p.iter().any(|s| s.starts_with("rm ")
|| s.starts_with("git ")
|| s.starts_with("chmod ")),
"{cmd}: {p:?}"
);
}
}
#[test]
fn the_psql_reader_trusts_only_display_meta_commands() {
let mut env = crate::env::MockEnvironment {
cwd: "/home/dev/projects/webapp".into(),
home: Some("/home/dev".into()),
..Default::default()
};
for (name, text) in [
("report.sql", "SELECT count(*) FROM orders;\n"),
(
"display.sql",
"\\timing on\n\\x\n\\echo report\n\\pset format aligned\n\\set ON_ERROR_STOP 1\n\\conninfo\n\\d+ orders\n\\c warehouse\nSELECT '2024-01-01'::date, a[1:2], 'x:y' FROM t; -- :z\n\\q\n",
),
("setvar.sql", "\\set q 'DROP TABLE orders'\n:q;\n"),
("quoted_var.sql", "SELECT * FROM :\"t\";\n"),
("copyenv.sql", "\\copy orders TO '/home/dev/projects/webapp/.env'\n"),
("oredir.sql", "SELECT 1;\n\\o /home/dev/.bashrc\nSELECT 'x';\n"),
("pager.sql", "\\pset pager on\nSELECT 1;\n"),
("setother.sql", "\\set PROMPT1 x\nSELECT 1;\n"),
("lo.sql", "SELECT lo_unlink(16400);\n"),
] {
env.files.insert(
format!("/home/dev/projects/webapp/queries/{name}").into(),
text.into(),
);
}
let ids = |cmd: &str| {
let settings = Settings::default();
let resolved = settings.resolved_for(crate::config::Mode::Shell);
let checks = get_all().unwrap();
let re = Regex::new("x").unwrap();
let p = analyze_command(cmd, &settings, &resolved, &checks, &env, &re).unwrap();
p.active_matches
.iter()
.map(|c| c.id.clone())
.collect::<Vec<_>>()
};
for cmd in [
"psql < queries/report.sql",
"psql -d warehouse < queries/display.sql",
"psql -f queries/display.sql",
"psql -X -q -A -t -d warehouse < queries/display.sql",
"psql -d warehouse -v ON_ERROR_STOP=1 < queries/report.sql",
"psql -U ro -h db -p 5432 -w -x --csv -1 -e -a -b -d warehouse < queries/report.sql",
"psql -c '\\i queries/report.sql'",
] {
assert!(ids(cmd).is_empty(), "{cmd}: {:?}", ids(cmd));
}
for cmd in [
"psql < queries/setvar.sql",
"psql < queries/quoted_var.sql",
"psql < queries/copyenv.sql",
"psql < queries/oredir.sql",
"psql -f queries/oredir.sql",
"psql < queries/pager.sql",
"psql < queries/setother.sql",
"psql < queries/lo.sql",
"cat queries/setvar.sql | psql",
"cat queries/copyenv.sql | psql",
"cat queries/oredir.sql | psql",
"cat queries/lo.sql | psql",
"docker exec -i pg psql < queries/setvar.sql",
"kubectl exec -i pg-0 -- psql < queries/setvar.sql",
"cat queries/report.sql | psql -d warehouse -o .envrc",
"cat queries/report.sql | psql -d warehouse -L ~/.bashrc",
"cat queries/report.sql | psql -d warehouse --output=x.txt",
"cat queries/report.sql | psql -d w -v q='DROP TABLE orders'",
"cat queries/report.sql | psql -d w --set=q=x",
"PSQLRC=/tmp/drop.sql psql < queries/report.sql",
"PSQLRC=/tmp/drop.sql psql -d warehouse -c 'select 1'",
"env PSQLRC=/tmp/drop.sql psql -d warehouse < queries/report.sql",
"export PSQLRC=/tmp/drop.sql; psql -d warehouse < queries/report.sql",
"psql < queries/report.sql; clickhouse-client < queries/drop.sql",
"psql < queries/report.sql && cockroach sql < queries/drop.sql",
"psql < queries/report.sql; psql -c '\\i /dev/null/unknown-sql-input'",
] {
assert!(!ids(cmd).is_empty(), "{cmd}");
}
}
#[cfg(unix)]
#[test]
fn privileged_lines_keep_only_the_exemptions_that_change_nothing() {
let tree = tree_fs::TreeBuilder::default().create().unwrap();
let root = tree.root.clone();
std::fs::create_dir_all(root.join("node_modules/.cache")).unwrap();
let mut env = crate::env::MockEnvironment {
cwd: root.clone(),
home: root.parent().map(std::path::Path::to_path_buf),
..Default::default()
};
env.existing_paths.insert(root.join("node_modules"));
env.existing_paths.insert(root.join("node_modules/.cache"));
let run = |cmd: &str| {
let settings = Settings::default();
let resolved = settings.resolved_for(crate::config::Mode::Shell);
let checks = get_all().unwrap();
let re = Regex::new("x").unwrap();
analyze_command(cmd, &settings, &resolved, &checks, &env, &re).unwrap()
};
for (cmd, as_root) in [
("sudo rm -rf node_modules", true),
("doas rm -rf node_modules/.cache", true),
("sh -c 'sudo rm -rf node_modules'", true),
("cd . && sudo rm -rf node_modules", true),
] {
let p = run(cmd);
let ids: Vec<&str> = p.active_matches.iter().map(|c| c.id.as_str()).collect();
assert_eq!(ids, ["fs-strict:recursive_deletion"], "{cmd}");
assert_eq!(p.relevant_context.is_root, as_root, "{cmd}");
assert!(
!p.command_parts
.iter()
.filter(|s| s.starts_with(PRIVILEGED_MARKER))
.any(|s| s.contains("shellfirm-privileged shellfirm-")),
"{cmd}: a marker segment is not copied"
);
}
for cmd in [
"rm -rf node_modules",
"env rm -rf node_modules",
"sudo cd . && rm -rf node_modules",
"sudo zfs destroy -nv tank/old",
"sudo kubectl drain node1 --dry-run=client",
"sudo npm unpublish my-pkg@1.0.0 --dry-run",
] {
assert!(run(cmd).active_matches.is_empty(), "{cmd}");
}
}
#[test]
fn privilege_survivors_are_built_in_checks() {
for id in PRIVILEGE_SURVIVORS {
assert!(
all_checks_cached().iter().any(|c| c.id == *id),
"{id} is not a built-in check"
);
}
}
#[test]
fn the_find_cache_exemption_uses_the_skipped_cache_names() {
let check = all_checks_cached()
.iter()
.find(|c| c.id == "fs:delete_find_files_filtered")
.unwrap();
let exemption = check
.filters
.iter()
.find_map(|f| match f {
Filter::NotMatches(re) if re.contains("node_modules") => Some(re.clone()),
_ => None,
})
.unwrap();
for name in SKIPPED_CACHE_DIRS {
assert!(
exemption.contains(&name.replace('.', "\\.")),
"{name} is missing"
);
}
}
#[test]
fn can_check_custom_filter_with_missing_capture_group() {
let filters = vec![Filter::PathExists(5)];
let check = Check {
id: "test-missing-group".to_string(),
test: Regex::new("rm (.*)").unwrap().into(),
description: "some description".to_string(),
from: "test".to_string(),
challenge: Challenge::default(),
filters,
alternative: None,
alternative_info: None,
severity: Severity::default(),
};
let env = crate::env::MockEnvironment::default();
assert!(!check_custom_filter_with_env(&check, "rm /tmp/foo", &env));
}
#[test]
fn can_check_multiple_filters_all_must_pass() {
let filters = vec![
Filter::NotContains("--dry-run".to_string()),
Filter::NotContains("--check".to_string()),
];
let check = Check {
id: "id".to_string(),
test: Regex::new("(delete)").unwrap().into(),
description: "some description".to_string(),
from: "test".to_string(),
challenge: Challenge::default(),
filters,
alternative: None,
alternative_info: None,
severity: Severity::default(),
};
let env = crate::env::MockEnvironment::default();
assert!(check_custom_filter_with_env(&check, "delete", &env));
assert!(!check_custom_filter_with_env(
&check,
"delete --dry-run",
&env
));
assert!(!check_custom_filter_with_env(
&check,
"delete --check",
&env
));
assert!(!check_custom_filter_with_env(
&check,
"delete --dry-run --check",
&env
));
}
#[test]
fn can_get_all_checks() {
assert_debug_snapshot!(get_all().is_ok());
}
#[test]
fn test_split_command_and_and() {
let parts = split_command("ls && rm -rf /");
assert_eq!(parts, vec!["ls ", " rm -rf /"]);
}
#[test]
fn test_split_command_pipe() {
let parts = split_command("cat foo | grep bar");
assert_eq!(parts, vec!["cat foo ", " grep bar"]);
}
#[test]
fn test_split_command_mixed() {
let parts = split_command("a && b || c; d");
assert_eq!(parts, vec!["a ", " b ", " c", " d"]);
}
#[test]
fn test_split_command_single() {
let parts = split_command("git push -f");
assert_eq!(parts, vec!["git push -f"]);
}
#[test]
fn test_split_command_double_quoted_operator() {
let parts = split_command(r#"echo "hello && world""#);
assert_eq!(parts, vec![r#"echo "hello && world""#]);
}
#[test]
fn test_split_command_single_quoted_pipe() {
let parts = split_command("echo 'a | b'");
assert_eq!(parts, vec!["echo 'a | b'"]);
}
#[test]
fn test_split_command_quoted_then_operator() {
let parts = split_command(r#"echo "safe" && rm -rf /"#);
assert_eq!(parts, vec![r#"echo "safe" "#, " rm -rf /"]);
}
#[test]
fn test_all_builtin_checks_pass_validation() {
let checks = get_all().unwrap();
let warnings = validate_checks(&checks);
assert!(
warnings.is_empty(),
"Built-in checks have validation warnings:\n{}",
warnings.join("\n")
);
}
#[test]
fn test_fill_alternative() {
assert_eq!(
fill_alternative("trash <path>", "rm -rf build dist"),
"trash build dist"
);
assert_eq!(
fill_alternative("git branch -d <branch>", "git branch -D feature/login"),
"git branch -d feature/login"
);
assert_eq!(
fill_alternative(
"kubectl get all -n <namespace>",
"kubectl delete ns payments"
),
"kubectl get all -n payments"
);
assert_eq!(
fill_alternative(
"aws s3 ls s3://<bucket>",
"aws s3 rb s3://my-bucket --force"
),
"aws s3 ls s3://my-bucket"
);
assert_eq!(
fill_alternative("trash <path>", "rm -rf my\u{1}dir other"),
"trash 'my dir' other"
);
assert_eq!(fill_alternative("kill <pid>", "kill -9 123"), "kill <pid>");
assert_eq!(fill_alternative("no placeholder", "rm x"), "no placeholder");
}
fn check_with(id: &str, sev: Severity) -> Check {
Check {
id: id.to_string(),
test: Regex::new("x").unwrap().into(),
description: String::new(),
from: "fs".to_string(),
challenge: Challenge::default(),
filters: vec![],
alternative: None,
alternative_info: None,
severity: sev,
}
}
#[test]
fn test_ignore_hint_rules() {
let ctx = RuntimeContext::default();
let a = check_with("fs:recursively_delete_outside", Severity::High);
let b = check_with("fs-strict:recursive_deletion", Severity::Medium);
let hint = ignore_hint(&[&b, &a], &ctx, false).unwrap();
assert!(
hint.contains("`shellfirm config ignore fs:recursively_delete_outside && shellfirm config ignore fs-strict:recursive_deletion`"),
"{hint}"
);
assert!(hint.contains("broad catch-all"), "{hint}");
assert!(!hint.contains("<check-id>"));
let c = check_with("fs:recursively_delete", Severity::Critical);
assert!(ignore_hint(&[&c], &ctx, false).is_none());
assert!(ignore_hint(&[&a], &ctx, true).is_none());
let root = RuntimeContext {
is_root: true,
..Default::default()
};
assert!(ignore_hint(&[&a], &root, false).is_none());
let prod = RuntimeContext {
risk_level: context::RiskLevel::Critical,
..Default::default()
};
assert!(ignore_hint(&[&a], &prod, false).is_none());
}
#[test]
fn test_sensitive_path_and_repository_markers() {
let mut settings = Settings::default();
settings.context.sensitive_paths = vec!["~/.ssh".into()];
let resolved = settings.resolved_for(crate::config::Mode::Shell);
let checks = get_all().unwrap();
let mut env = crate::env::MockEnvironment {
cwd: "/home/dev/projects".into(),
home: Some("/home/dev".into()),
..Default::default()
};
env.files.insert(
"/home/dev/projects/webapp/.git/HEAD".into(),
"ref: refs/heads/main".into(),
);
let re = Regex::new("x").unwrap();
let p = analyze_command(
"cp evil ~/.ssh/authorized_keys",
&settings,
&resolved,
&checks,
&env,
&re,
)
.unwrap();
let ids: Vec<&str> = p.active_matches.iter().map(|c| c.id.as_str()).collect();
assert!(ids.contains(&"fs:sensitive_path"), "{ids:?}");
assert_eq!(p.context.risk_level, context::RiskLevel::Critical);
let p = analyze_command("rm -rf webapp", &settings, &resolved, &checks, &env, &re).unwrap();
let ids: Vec<&str> = p.active_matches.iter().map(|c| c.id.as_str()).collect();
assert!(ids.contains(&"fs:delete_repository"), "{ids:?}");
assert!(
p.alternatives
.iter()
.any(|a| a.suggestion == "trash webapp"),
"{:?}",
p.alternatives
);
let p = analyze_command(
"rm -rf webapp/src",
&settings,
&resolved,
&checks,
&env,
&re,
)
.unwrap();
assert!(!p
.active_matches
.iter()
.any(|c| c.id == "fs:delete_repository"));
}
#[test]
fn test_validate_catches_bad_capture_group() {
let checks = vec![Check {
id: "bad".to_string(),
test: Regex::new("rm (.*)").unwrap().into(),
description: "test".to_string(),
from: "test".to_string(),
challenge: Challenge::default(),
filters: vec![Filter::PathExists(5)], alternative: None,
alternative_info: None,
severity: Severity::default(),
}];
let warnings = validate_checks(&checks);
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains("PathExists(5)"));
}
#[test]
fn builtin_table_matches_yaml() {
let from_yaml: Vec<Check> = serde_yaml::from_str(ALL_CHECKS).unwrap();
let from_table = all_checks_cached();
assert_eq!(from_yaml.len(), from_table.len());
for (a, b) in from_yaml.iter().zip(from_table) {
assert_eq!(format!("{a:?}"), format!("{b:?}"));
assert_eq!(
serde_yaml::to_string(a).unwrap(),
serde_yaml::to_string(b).unwrap()
);
}
}
#[test]
fn builtin_checks_have_prefilters() {
let all = all_checks_cached();
let without: Vec<&str> = all
.iter()
.filter(|c| c.test.0.prefilter.is_none())
.map(|c| c.id.as_str())
.collect();
assert!(
without.is_empty(),
"checks without a prefilter: {without:?}"
);
}
#[test]
fn prefilter_never_changes_a_match() {
#[derive(Deserialize)]
struct Case {
test: String,
}
let mut commands: Vec<String> = Vec::new();
for (path, text) in fixture_files() {
let cases: Vec<Case> =
serde_yaml::from_str(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
commands.extend(cases.into_iter().map(|c| c.test));
}
assert!(commands.len() > 500, "corpus too small: {}", commands.len());
let variants: Vec<String> = commands
.iter()
.flat_map(|c| {
[
c.clone(),
c.to_uppercase(),
c.replace('k', "\u{212A}").replace('s', "\u{17F}"),
c.replace(' ', "\u{a0}"),
]
})
.collect();
let all = all_checks_cached();
let mut matched = 0usize;
for cmd in &variants {
let parsed = crate::parser::parse(cmd);
let mut texts = parsed.segments.clone();
texts.push(parsed.flat.clone());
texts.push(cmd.clone());
for text in &texts {
let folded = crate::prefilter::fold(text);
for c in all {
let full = c.test.regex().is_match(text);
matched += usize::from(full);
assert_eq!(
c.test.is_match_prefiltered(text, &folded),
full,
"check {} on {text:?}",
c.id
);
}
}
}
assert!(matched > 500);
}
#[test]
fn check_regex_behaves_like_regex() {
let lazy = CheckRegex::lazy("(?i)DROP\\s+(table)".to_string(), Some(&["drop"]));
assert_eq!(lazy.as_str(), "(?i)DROP\\s+(table)");
assert!(lazy.0.compiled.get().is_none(), "as_str must not compile");
assert!(!lazy.is_match_prefiltered("ls", "ls"));
assert!(
lazy.0.compiled.get().is_none(),
"a prefilter miss must not compile"
);
assert!(lazy.is_match_prefiltered("Drop TABLE", "drop table"));
assert_eq!(lazy.captures_len(), 2);
let clone = lazy.clone();
assert!(
clone.0.compiled.get().is_some(),
"clones share the compiled regex"
);
assert_eq!(
format!("{lazy:?}"),
format!("{:?}", Regex::new(lazy.as_str()).unwrap())
);
assert_eq!(
serde_yaml::to_string(&lazy).unwrap(),
serde_yaml::to_string(lazy.as_str()).unwrap()
);
let err = serde_yaml::from_str::<CheckRegex>("\"(unclosed\"").unwrap_err();
let want = serde_yaml::from_str::<Wrapped>("\"(unclosed\"").unwrap_err();
assert_eq!(err.to_string(), want.to_string());
#[derive(Debug, Deserialize)]
struct Wrapped(
#[serde(with = "serde_regex")]
#[allow(dead_code)]
Regex,
);
}
}
#[cfg(test)]
mod test_uncommitted_work {
use super::*;
#[test]
fn deleted_folder_operands_cover_every_spelling() {
assert_eq!(deleted_folder_operands("rm -rf docs"), vec!["docs"]);
assert_eq!(deleted_folder_operands("rm -rf docs/*"), vec!["docs"]);
assert_eq!(deleted_folder_operands("rm -rf docs/."), vec!["docs"]);
assert_eq!(deleted_folder_operands("rm -r a b"), vec!["a", "b"]);
assert!(deleted_folder_operands("rm -f docs").is_empty());
assert!(deleted_folder_operands("rm -rf docs/*.log").is_empty());
assert_eq!(deleted_folder_operands("find docs -delete"), vec!["docs"]);
assert_eq!(
deleted_folder_operands("find docs -mindepth 1 -delete"),
vec!["docs"]
);
assert!(deleted_folder_operands("find docs -name *.pyc -delete").is_empty());
assert!(deleted_folder_operands("find docs -type f").is_empty());
assert_eq!(deleted_folder_operands("mv docs /tmp/old"), vec!["docs"]);
assert_eq!(
deleted_folder_operands("mv -f a b /var/tmp/"),
vec!["a", "b"]
);
assert!(deleted_folder_operands("mv docs docs-old").is_empty());
}
fn analyze(cmd: &str, env: &crate::env::MockEnvironment) -> Vec<(String, Severity, String)> {
let mut settings = Settings::default();
settings.min_severity = Some(Severity::High);
let resolved = settings.resolved_for(crate::config::Mode::Shell);
let checks = get_all().unwrap();
let re = Regex::new("x").unwrap();
let p = analyze_command(cmd, &settings, &resolved, &checks, env, &re).unwrap();
p.active_matches
.iter()
.map(|c| (c.id.clone(), c.severity, c.description.clone()))
.collect()
}
fn matched_ids(cmd: &str, env: &crate::env::MockEnvironment) -> Vec<String> {
let settings = Settings::default();
let resolved = settings.resolved_for(crate::config::Mode::Shell);
let checks = get_all().unwrap();
let re = Regex::new("x").unwrap();
let p = analyze_command(cmd, &settings, &resolved, &checks, env, &re).unwrap();
p.active_matches.iter().map(|c| c.id.clone()).collect()
}
#[cfg(unix)]
#[test]
fn cache_folders_and_dotfiles_are_skipped_only_when_real() {
let tree = tree_fs::TreeBuilder::default().create().unwrap();
let root = tree.root.clone();
for d in [
"node_modules/.cache",
"__pycache__",
".next/cache",
".venv/lib",
"src/lib",
"pkg",
".git",
] {
std::fs::create_dir_all(root.join(d)).unwrap();
}
std::fs::write(root.join(".env"), "A=1").unwrap();
std::os::unix::fs::symlink("../src", root.join("pkg/node_modules")).unwrap();
std::os::unix::fs::symlink("../src", root.join("pkg/.next")).unwrap();
std::os::unix::fs::symlink(".git", root.join(".envrc")).unwrap();
let mut env = crate::env::MockEnvironment {
cwd: root.clone(),
home: root.parent().map(std::path::Path::to_path_buf),
..Default::default()
};
for p in [
"node_modules",
"node_modules/.cache",
"__pycache__",
"src",
"src/lib",
"pkg",
"pkg/node_modules",
"pkg/node_modules/lib",
".next",
".venv",
"pkg/.next",
"yarn.lock",
".git",
".env",
".envrc",
] {
env.existing_paths.insert(root.join(p));
}
for cmd in [
"rm -rf node_modules",
"rm -rf node_modules/.cache",
"rm -rf __pycache__",
"rm -rf .next",
"rm -rf node_modules yarn.lock",
"npx rimraf node_modules",
"chmod 600 .env",
] {
let ids = matched_ids(cmd, &env);
assert!(!ids.iter().any(|i| i.starts_with("fs")), "{cmd}: {ids:?}");
}
for (cmd, id) in [
("rm -rf pkg/node_modules", "fs-strict:recursive_deletion"),
("rm -rf pkg/node_modules/", "fs-strict:recursive_deletion"),
(
"rm -rf pkg/node_modules/lib",
"fs-strict:recursive_deletion",
),
("rm -rf pkg/.next", "fs-strict:recursive_deletion"),
("rm -rf node_modules/", "fs-strict:recursive_deletion"),
("rm -rf .next/", "fs-strict:recursive_deletion"),
("rm -rf .venv/*/..", "fs-strict:recursive_deletion"),
("chmod 600 .git", "fs-strict:change_permissions"),
("chmod 600 .envrc", "fs-strict:change_permissions"),
] {
let ids = matched_ids(cmd, &env);
assert!(ids.iter().any(|i| i == id), "{cmd}: {ids:?}");
}
}
#[test]
fn dirty_or_unchecked_folders_stay_high_in_every_spelling() {
let tree = tree_fs::TreeBuilder::default().create().unwrap();
let root = tree.root.clone();
for d in ["docs", "src", "lib", "日本"] {
std::fs::create_dir_all(root.join(d)).unwrap();
std::fs::write(root.join(d).join("f.txt"), "x").unwrap();
}
let r = root.display().to_string();
let mut env = crate::env::MockEnvironment {
cwd: root.clone(),
home: Some("/home/nobody".into()),
..Default::default()
};
env.files
.insert(root.join(".git/HEAD"), "ref: refs/heads/main".into());
for d in ["docs", "src", "lib", "日本"] {
env.existing_paths.insert(root.join(d));
}
let status =
|p: &str| format!("git -C {r} status --porcelain --untracked-files=normal -- {p}");
env.command_outputs
.insert(status("docs"), "?? docs/".into());
env.command_outputs.insert(status("lib"), String::new());
env.command_outputs
.insert(status("日本"), r#"?? "\346\227\245\346\234\254/""#.into());
env.timed_out_commands.insert(status("src"));
for cmd in [
"rm -rf docs",
"rm -rf docs/*",
"cd docs && rm -rf *",
"find docs -delete",
"mv docs /tmp/docs-old",
"rm -rf 日本",
] {
let m = analyze(cmd, &env);
assert!(
m.iter().any(|(_, s, d)| *s == Severity::High
&& d.contains("uncommitted or untracked files")),
"{cmd}: {m:?}"
);
}
let m = analyze("rm -rf src", &env);
assert!(
m.iter().any(|(_, s, d)| *s == Severity::High
&& d.contains("could not check for uncommitted files in time")),
"{m:?}"
);
let m = analyze("rm -rf lib", &env);
assert!(m.is_empty(), "{m:?}");
}
#[test]
fn git_quoted_paths_are_unquoted() {
assert_eq!(unquote_git_path("docs/"), "docs/");
assert_eq!(unquote_git_path(r#""\346\227\245\346\234\254/""#), "日本/");
assert_eq!(unquote_git_path(r#""a\"b\\c\td""#), "a\"b\\c\td");
}
#[test]
fn restoring_a_path_without_changes_is_not_asked() {
assert_eq!(
restored_paths("git restore src/a.js"),
Some(vec!["src/a.js".to_string()])
);
assert_eq!(
restored_paths("git checkout -- a b"),
Some(vec!["a".to_string(), "b".to_string()])
);
assert!(restored_paths("git restore --source=HEAD~5 a").is_none());
assert!(restored_paths("git restore -s HEAD~1 a").is_none());
assert!(restored_paths("git checkout main -- a").is_none());
assert!(restored_paths("git restore .").is_none());
let mut env = crate::env::MockEnvironment {
cwd: "/repo".into(),
..Default::default()
};
env.command_outputs.insert(
"git status --porcelain --untracked-files=no -- clean.js".into(),
String::new(),
);
env.command_outputs.insert(
"git status --porcelain --untracked-files=no -- dirty.js".into(),
" M dirty.js".into(),
);
let ids = |cmd: &str| -> Vec<String> {
let settings = Settings::default();
let resolved = settings.resolved_for(crate::config::Mode::Shell);
let checks = get_all().unwrap();
let re = Regex::new("x").unwrap();
analyze_command(cmd, &settings, &resolved, &checks, &env, &re)
.unwrap()
.active_matches
.iter()
.map(|c| c.id.clone())
.collect()
};
assert!(ids("git restore clean.js").is_empty());
assert!(ids("git restore dirty.js").contains(&"git:restore_discard_path".to_string()));
assert!(ids("git restore unknown.js").contains(&"git:restore_discard_path".to_string()));
}
}