#[allow(dead_code)]
#[path = "../src/tripwire.rs"]
mod tripwire;
mod original {
pub fn has_cmd_tags(tags: &str) -> bool {
tags.split(';').any(|t| t.trim().to_lowercase().starts_with("cmd:"))
}
pub fn cmd_specs_tags(tags: &str) -> Vec<String> {
let mut v: Vec<String> = tags.split(';').map(str::trim).filter(|t| t.to_lowercase().starts_with("cmd:")).map(str::to_owned).collect();
v.sort();
v
}
pub fn words(command: &str) -> Vec<String> {
let mut s = String::with_capacity(command.len() + 8);
let mut chars = command.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' | '\'' | '`' => {}
';' | '|' | '&' | '(' | ')' => s.push(' '),
'>' => {
if chars.peek() == Some(&'>') {
chars.next();
s.push_str(" >> ");
} else {
s.push_str(" > ");
}
}
c => s.push(c),
}
}
s.split_whitespace().map(str::to_owned).collect()
}
fn token_hits(tok: &str, word: &str) -> bool {
match tok.strip_prefix('*') {
Some("") => word == "*",
Some(sub) => word.contains(sub) || (!sub.starts_with('-') && word.to_lowercase().contains(&sub.to_lowercase())),
None => word == tok || (tok.chars().all(|c| c.is_ascii_alphabetic()) && word.eq_ignore_ascii_case(tok)),
}
}
pub fn spec_matches(spec: &str, words: &[String]) -> Option<usize> {
let mut at = 0;
let mut positive = 0;
for tok in spec.split_whitespace() {
if let Some(neg) = tok.strip_prefix('!') {
if words.iter().any(|w| token_hits(neg, w)) {
return None;
}
continue;
}
let found = words.iter().skip(at).position(|w| token_hits(&tok, w))?;
at += found + 1;
positive += 1;
}
(positive > 0).then_some(positive)
}
pub fn best_match(tags: &str, w: &[String]) -> Option<usize> {
let mut best: Option<usize> = None;
for t in tags.split(';') {
let t = t.trim();
let Some(spec) = t.get(..4).filter(|p| p.eq_ignore_ascii_case("cmd:")).map(|_| &t[4..]) else {
continue;
};
if let Some(n) = spec_matches(spec, w) {
if best.is_none_or(|b| n > b) {
best = Some(n);
}
}
}
best
}
}
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n as u64) as usize
}
fn pick<'a>(&mut self, v: &[&'a str]) -> &'a str {
v[self.below(v.len())]
}
}
const WORDS: &[&str] = &[
"git", "push", "--force", "-f", "--force-with-lease", "origin", "main", "rm", "-rf", "-RF", "-r", "-D", "-d", "branch", "reset", "--hard",
"DELETE", "delete", "FROM", "from", "users", "WHERE", "where", "id=1", "psql", "-c", "flushall", "FLUSHALL", "redis-cli", "chmod", "-R", "777",
"/", "~", "~/.bashrc", ".bashrc", "$BUILD", "${BUILD:?}", "*", "./target", "/*", "docker", "system", "prune", "-a", "kubectl", "drop",
"table", "DROP", "TABLE", "sudo", "curl", "|", "sh", "dd", "if=/dev/zero", "of=/dev/sda", "mkfs", "ls", "cat", "echo", "cd", "x", "&&", "||", ";",
">", ">>", "2>&1", "-9", "kill", "pkill", "-f", "server", "npm", "publish", "terraform", "destroy", "--force-push", "Ünï", "ÄÖ", "İ", "ß", "日本",
];
const TOKENS: &[&str] = &[
"git", "push", "--force", "-f", "-D", "-d", "rm", "-rf", "-r", "*$", "*:?", "!*:?", "*", "!*", "!where", "!WHERE", "delete", "from", "DELETE", "FROM",
"where", "flushall", "!--force-with-lease", ">", ">>", "*.bashrc", "*.BASHRC", "*-RF", "*-rf", "*日本", "*ß", "*SS", "*İ", "!", "!!", "*!", "chmod",
"777", "*77", "!777", "drop", "TABLE", "table", "!table", "sudo", "!sudo", "*/", "/", "~", "origin", "main", "--hard", "reset", "dd", "if=*", "*=/dev/*",
"ÄÖ", "äö", "ä", "x", "ls", "!ls", "docker", "prune", "-a", "kill", "-9",
];
const SEPARATORS: &[&str] = &[" ", " ", " ", " ", "\t", " && ", " | ", "; ", " > ", ">", ">>", " >> ", "(", ")", "\"", "'", "`", "\n"];
fn command(r: &mut Rng) -> String {
let n = r.below(14);
let mut s = String::new();
for i in 0..n {
if i > 0 || r.below(8) == 0 {
s.push_str(r.pick(SEPARATORS));
}
if r.below(6) == 0 {
s.push_str(r.pick(SEPARATORS));
}
s.push_str(r.pick(WORDS));
}
s
}
fn spec(r: &mut Rng) -> String {
let n = r.below(6);
let mut s = String::new();
for i in 0..n {
if i > 0 {
s.push_str(r.pick(&[" ", " ", " ", " ", "\t"]));
}
s.push_str(r.pick(TOKENS));
}
s
}
fn tags(r: &mut Rng) -> String {
let n = r.below(5);
let mut parts: Vec<String> = Vec::new();
for _ in 0..n {
let body = spec(r);
let t = match r.below(9) {
0 => format!("cmd:{body}"),
1 => format!("CMD:{body}"),
2 => format!("Cmd: {body}"),
3 => format!(" cmd:{body} "),
4 => format!("cmd {body}"),
5 => format!("cmd:{body}ä"),
6 => "ünï".to_string(),
7 => "safety".to_string(),
_ => format!("cmd:{body}"),
};
parts.push(t);
}
parts.join(r.pick(&[";", "; ", " ; ", ";"]))
}
fn pack_specs() -> Vec<String> {
let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/community/tripwires.json")).unwrap();
let mut out = Vec::new();
for part in text.split("cmd:").skip(1) {
let end = part.find([';', '"']).unwrap_or(part.len());
out.push(part[..end].to_string());
}
out.retain(|s| !s.split_whitespace().any(|t| t.trim_start_matches(['!', '<']).starts_with('=') || t.starts_with('<')));
out
}
#[test]
fn command_words_equal_words_when_no_segment_only_reads() {
let mut r = Rng(0x51ED_270B_0F3A_9C17);
let reading = ["echo", "cat", "ls"];
let (mut same, mut skipped) = (0u32, 0u32);
for _ in 0..30_000 {
let cmd = command(&mut r);
let w = tripwire::words(&cmd);
if reading.iter().any(|r| cmd.contains(r)) {
skipped += 1;
continue;
}
assert_eq!(tripwire::command_words(&cmd), w, "{cmd:?}");
same += 1;
}
println!("command_words equals words on {same} generated commands ({skipped} with a reading word skipped)");
assert!(same > 10_000);
}
fn cw(cmd: &str) -> Vec<String> {
tripwire::command_words(cmd)
}
#[test]
fn text_given_to_a_reading_command_is_not_a_command() {
for c in [
"grep -rn mkfs docs/",
"echo \"do not run mkfs here\"",
"echo 'rm -rf /' ; ls",
"man dd",
"cat notes.md | grep 'git push --force'",
"git log --grep=\"git reset --hard\"",
"sudo -u dev rg 'DROP TABLE' src",
"FOO=1 printf '%s\\n' \"kubectl delete ns prod\"",
"ls /sbin/mkfs*",
"echo \"a; rm -rf /\"",
"echo 'a | rm -rf /' | head -1",
"find . -name x | xargs grep -n mkfs",
] {
let w = cw(c);
for bad in ["mkfs", "rm", "dd", "push", "reset", "DROP", "kubectl", "/sbin/mkfs*"] {
assert!(!w.iter().any(|x| x == bad), "{c:?} kept {bad}: {w:?}");
}
}
}
#[test]
fn commands_that_run_stay_whole() {
let w = cw("sudo mkfs.ext4 /dev/sdb1");
assert_eq!(w, ["sudo", "mkfs.ext4", "/dev/sdb1"]);
assert_eq!(cw("find . -name x | xargs rm -rf"), ["find", ".", "-name", "x", "xargs", "rm", "-rf"]);
assert_eq!(cw("echo 'rm -rf /' | sh"), ["echo", "rm", "-rf", "/", "sh"]);
assert_eq!(cw("echo \"DROP TABLE users\" | sudo -u pg psql db"), ["echo", "DROP", "TABLE", "users", "sudo", "-u", "pg", "psql", "db"]);
assert_eq!(cw("cd /tmp && rm -rf *"), ["cd", "/tmp", "rm", "-rf", "*"]);
}
#[test]
fn a_reading_command_keeps_its_real_redirects_only() {
assert_eq!(cw("echo hi > ~/.bashrc"), [">", "~/.bashrc"]);
assert_eq!(cw("cat disk.img >> /dev/sdb"), [">>", "/dev/sdb"]);
assert!(cw("echo 'a > ~/.bashrc'").is_empty());
assert!(cw("echo \"a > ~/.bashrc\" | wc -l").is_empty());
assert!(cw("echo \"say \\\"hi\\\" ; rm -rf /\"").is_empty());
}
fn fires(spec: &str, cmd: &str) -> bool {
tripwire::spec_matches(spec, &tripwire::words(cmd)).is_some()
}
#[test]
fn equals_tokens_match_whole_words_without_case() {
assert!(fires("rm =-rf|-fr", "rm -RF x"));
assert!(fires("rm =-rf|-fr", "sudo rm -fr x"));
assert!(!fires("rm =-rf|-fr", "rm -rfv x"));
assert!(!fires("rm =-rf|-fr", "rm -r -f x"));
assert!(!fires("rm =|", "rm x"));
assert!(fires("dd *of=/dev/", "dd of=/dev/sdb"));
}
#[test]
fn question_mark_is_one_path_segment() {
let spec = "rm =/home/?|/home/?/*";
for yes in ["rm -rf /home/leduc", "rm -rf /HOME/Leduc/", "rm -rf /home/leduc/*", "rm /home/ünï"] {
assert!(fires(spec, yes), "{yes}");
}
for no in ["rm -rf /home", "rm -rf /home/", "rm -rf /home/leduc/project", "rm -rf /home/leduc/*/x", "rm -rf /home/*", "rm -rf /homes/leduc", "rm -rf ~/home/leduc"] {
assert!(!fires(spec, no), "{no}");
}
}
#[test]
fn caret_accepts_every_cut_short_form() {
let spec = "=remove-item =-r^ecurse";
for yes in ["Remove-Item -r x", "Remove-Item -Rec x", "Remove-Item -RECURSE x", "Remove-Item x -recurse"] {
assert!(fires(spec, yes), "{yes}");
}
for no in ["Remove-Item -rf x", "Remove-Item -recursed x", "Remove-Item -rx x", "Remove-Item x"] {
assert!(!fires(spec, no), "{no}");
}
assert!(fires("x =-fo^rce", "x -fo") && fires("x =-fo^rce", "x -Force"));
assert!(!fires("x =-fo^rce", "x -f") && !fires("x =-fo^rce", "x -fi"));
}
#[test]
fn star_and_plus_alternatives_in_equals_tokens() {
let drive = "rd =*:\\|*:/|*%|**|\\+";
for yes in ["rd C:\\", "rd c:/x", "rd %TEMP%\\x", "rd *.tmp", "rd \\\\srv\\share", "rd D:\\a\\b"] {
assert!(fires(drive, yes), "{yes}");
}
for no in ["rd build", "rd .\\build", "rd out\\obj", "rd ./x"] {
assert!(!fires(drive, no), "{no}");
}
let home = "rm =$home/+|${home}/+";
for yes in ["rm $HOME/code", "rm \"$HOME\"/a/b/", "rm ${HOME}/.cache/pip", "rm $HOME/.cache"] {
assert!(fires(home, yes), "{yes}");
}
for no in ["rm $HOME", "rm $HOME/", "rm $HOME/*", "rm $HOME/.*", "rm $HOME/.[a-z]*", "rm $HOMEDIR/x", "rm ${HOME}", "rm $BUILD/x"] {
assert!(!fires(home, no), "{no}");
}
}
#[test]
fn a_bang_alternative_vetoes_the_word() {
let spec = "rm =*$|!$home/+|!${home}/+";
for yes in ["rm $OTHER/*", "rm $HOME", "rm $HOME/*", "rm $HOME/$SUB", "rm $HOME/x $OTHER/*", "rm $HOME/x && rm $DIR/"] {
assert!(fires(spec, yes), "{yes}");
}
for no in ["rm $HOME/x", "rm \"$HOME/a\" \"$HOME/b\"", "rm ${HOME}/a/b", "rm build"] {
assert!(!fires(spec, no), "{no}");
}
}
#[test]
fn a_gap_token_forbids_words_before_the_next_match() {
let spec = "find <=-name|-type <*-newer -delete";
assert!(fires(spec, "find . -delete"));
assert!(fires(spec, "find ~/x -delete -name '*.tmp'"));
assert!(fires(spec, "find . -maxdepth 1 -delete"));
assert!(!fires(spec, "find . -name '*.tmp' -delete"));
assert!(!fires(spec, "find . -type f -delete"));
assert!(!fires(spec, "find . -newermt 2026-01-01 -delete"));
assert!(fires("find <=-name -prune -delete", "find -prune -delete"));
assert!(!fires("find -prune <=-name -delete", "find -prune -name x -delete"));
}
#[test]
fn a_negated_equals_token_silences_the_spec() {
let spec = "=remove-item =-r^ecurse !=-w^hatif";
assert!(fires(spec, "Remove-Item -Recurse build"));
assert!(!fires(spec, "Remove-Item -Recurse -WhatIf build"));
assert!(!fires(spec, "Remove-Item -Recurse -wh build"));
}
#[test]
fn helix_matcher_equals_the_frozen_rust_matcher_on_over_a_hundred_thousand_cases() {
let mut r = Rng(0x9E37_79B9_7F4A_7C15);
let mut cases = 0u64;
let mut matched = 0u64;
let mut diffs: Vec<String> = Vec::new();
let mut check = |cmd: &str, spec: &str| {
let (a, b) = (original::words(cmd), tripwire::words(cmd));
cases += 1;
if a != b {
diffs.push(format!("words({cmd:?})"));
return;
}
let (x, y) = (original::spec_matches(spec, &a), tripwire::spec_matches(spec, &b));
if x.is_some() {
matched += 1;
}
if x != y {
diffs.push(format!("spec_matches({spec:?}, {cmd:?}): {x:?} vs {y:?}"));
}
};
for _ in 0..10_000 {
let cmd = command(&mut r);
for _ in 0..16 {
let sp = spec(&mut r);
check(&cmd, &sp);
}
}
let pack = pack_specs();
assert!(pack.len() >= 25, "pack specs read: {}", pack.len());
for _ in 0..2_000 {
let base = command(&mut r);
for sp in &pack {
check(&base, sp);
let mut planted = base.clone();
for tok in sp.split_whitespace().filter(|t| !t.starts_with('!')) {
planted.push(' ');
planted.push_str(tok.trim_start_matches('*'));
}
check(&planted, sp);
}
}
println!("tripwire differential: {cases} command x spec cases, {matched} matched, {} differences", diffs.len());
assert!(cases >= 100_000, "only {cases} cases");
assert!(matched >= 10_000, "only {matched} matching cases: the generator must reach the match path");
assert!(diffs.is_empty(), "{} differences, first: {:?}", diffs.len(), &diffs[..diffs.len().min(5)]);
}
#[test]
fn helix_tag_helpers_equal_the_frozen_rust_on_generated_tag_lists() {
let mut r = Rng(0xD1B5_4A32_D192_ED03);
let mut cases = 0u64;
let mut with_match = 0u64;
for _ in 0..30_000 {
let tg = tags(&mut r);
assert_eq!(original::has_cmd_tags(&tg), tripwire::has_cmd(&tg), "has_cmd({tg:?})");
assert_eq!(original::cmd_specs_tags(&tg), tripwire::cmd_specs(&tg), "cmd_specs({tg:?})");
for _ in 0..4 {
let w = original::words(&command(&mut r));
let (x, y) = (original::best_match(&tg, &w), tripwire::best_match(&tg, &w));
assert_eq!(x, y, "best_match({tg:?}, {w:?})");
cases += 1;
if x.is_some() {
with_match += 1;
}
}
}
println!("tripwire differential: {cases} tag-list x command cases for best_match, {with_match} matched");
assert!(with_match >= 1_000, "only {with_match} matching tag lists");
}