diff --git a/README.md b/README.md index a2966ee..74d753e 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,12 @@ Try both commands on the rules in `examples/settings.json`. allow git status <- Bash(git *) in examples/settings.json no rule npm test +**Why was this file read allowed?** + + $ python3 plugin/scripts/permwhy.py --settings examples/settings.json explain --tool Read src/main.py + $ python3 plugin/scripts/permwhy.py --settings examples/settings.json explain --tool Edit src/main.py + +Use `--tool Read` or `--tool Edit` to explain file permission decisions. The default remains `Bash`. **Which rules have problems?** (excerpt) $ python3 plugin/scripts/permwhy.py --settings examples/settings.json lint diff --git a/examples/settings.json b/examples/settings.json index 90221d2..84d766a 100644 --- a/examples/settings.json +++ b/examples/settings.json @@ -2,6 +2,8 @@ "permissions": { "allow": [ "Bash(git *)", + "Read(src/**)", + "Edit(src/**)", "Bash(python *)", "Bash(aws s3 ls)", "Bash(curl http://github.com/ *)" diff --git a/plugin/scripts/permwhy.py b/plugin/scripts/permwhy.py index 227201e..f8a2cd5 100644 --- a/plugin/scripts/permwhy.py +++ b/plugin/scripts/permwhy.py @@ -8,6 +8,7 @@ import argparse import fnmatch import json +import posixpath import re import shlex import sys @@ -41,6 +42,7 @@ class Rule: text: str source: str pattern: str | None = None + tool: str = "Bash" @dataclass @@ -267,9 +269,17 @@ def parse_rule(kind, text, source): match = RULE_PATTERN.match(text.strip()) if not match: return None - if match.group(1) != "Bash": - return Rule(kind, text, source, pattern=None) - return Rule(kind, text, source, pattern=match.group(2) if match.group(2) is not None else "*") + + tool = match.group(1) + pattern = match.group(2) if match.group(2) is not None else "*" + + return Rule( + kind, + text, + source, + pattern=pattern, + tool=tool, + ) def pattern_matches(pattern, command): @@ -285,6 +295,176 @@ def pattern_matches(pattern, command): return fnmatch.fnmatchcase(command, translated) + + +def _is_windows_path(path): + """Return whether a path uses Windows drive or UNC syntax.""" + value = str(path) + return ( + re.match(r"^[A-Za-z]:[\\/]", value) is not None + or value.startswith("\\\\") + or value.startswith("//") + ) + + +def _path_to_posix(path): + """Normalize Windows and POSIX paths to a comparable POSIX form.""" + original = str(path) + value = original.replace("\\", "/") + + # Windows drive paths: C:/foo -> /c/foo. + drive_match = re.match(r"^([A-Za-z]):/", value) + if drive_match: + return "/" + drive_match.group(1).lower() + value[2:] + + # UNC paths: \\server\share\foo -> /unc/server/share/foo. + if value.startswith("//"): + unc_parts = [part for part in value[2:].split("/") if part] + if len(unc_parts) >= 2: + return posixpath.normpath( + posixpath.join("/unc", *unc_parts) + ) + + return value + + +def _absolute_posix_path(path, cwd): + """Resolve a path against cwd and return its normalized POSIX form.""" + value = _path_to_posix(path) + + if not value.startswith("/"): + value = posixpath.join(cwd, value) + + return posixpath.normpath(value) + + +def _settings_source_root(source, cwd, home): + """Return the base directory used by source-relative permission patterns.""" + source_path = _absolute_posix_path( + Path(source).expanduser(), + cwd, + ) + + home_claude = posixpath.join(home, ".claude") + user_settings = posixpath.join(home_claude, "settings.json") + + if source_path == user_settings: + return home_claude + + source_dir = posixpath.dirname(source_path) + source_name = posixpath.basename(source_path) + + if ( + posixpath.basename(source_dir) == ".claude" + and source_name in {"settings.json", "settings.local.json"} + ): + return posixpath.dirname(source_dir) + + return source_dir + + +def path_pattern_matches(pattern, path, kind, source=None, cwd=None): + """Match Read/Edit paths using normalized glob-style path semantics.""" + raw_pattern = str(pattern) + raw_path = str(path) + + cwd_value = cwd if cwd is not None else Path.cwd() + cwd_posix = _absolute_posix_path(cwd_value, "/") + home = _absolute_posix_path(Path.home(), cwd_posix) + + windows_semantics = ( + _is_windows_path(raw_path) + or _is_windows_path(raw_pattern) + or _is_windows_path(cwd_value) + ) + + target = _absolute_posix_path(raw_path, cwd_posix) + + # Expand home-relative paths. + if raw_path.replace("\\", "/").startswith("~/"): + target = posixpath.normpath( + posixpath.join(home, raw_path.replace("\\", "/")[2:]) + ) + + pattern_slashes = raw_pattern.replace("\\", "/") + + if pattern_slashes.startswith("~/"): + resolved_pattern = posixpath.join( + home, + pattern_slashes[2:], + ) + + # A pattern beginning with // is the explicit filesystem-absolute + # pattern syntax. A Windows UNC pattern is written with backslashes. + elif raw_pattern.startswith("\\\\"): + resolved_pattern = _path_to_posix(raw_pattern) + + elif pattern_slashes.startswith("//"): + resolved_pattern = "/" + pattern_slashes.lstrip("/") + + elif pattern_slashes.startswith("/"): + source_root = ( + _settings_source_root(source, cwd_posix, home) + if source is not None + else cwd_posix + ) + resolved_pattern = posixpath.join( + source_root, + pattern_slashes.lstrip("/"), + ) + + elif re.match(r"^[A-Za-z]:/", pattern_slashes): + resolved_pattern = _path_to_posix(pattern_slashes) + + else: + relative_pattern = pattern_slashes.removeprefix("./") + resolved_pattern = posixpath.join( + cwd_posix, + relative_pattern, + ) + + # A pattern without a slash matches a filename at any depth + # beneath its selected base directory. + if ( + "/" not in pattern_slashes + and not pattern_slashes.startswith("/") + and not pattern_slashes.startswith("~/") + ): + resolved_pattern = posixpath.join( + cwd_posix, + "**", + pattern_slashes, + ) + + # Windows paths are case-insensitive. POSIX paths remain case-sensitive. + if windows_semantics: + target = target.casefold() + resolved_pattern = resolved_pattern.casefold() + + regex = [] + i = 0 + + while i < len(resolved_pattern): + if resolved_pattern.startswith("**/", i): + # **/ matches zero or more directory levels. + regex.append("(?:.*/)?") + i += 3 + elif resolved_pattern.startswith("**", i): + regex.append(".*") + i += 2 + elif resolved_pattern[i] == "*": + regex.append("[^/]*") + i += 1 + elif resolved_pattern[i] == "?": + regex.append("[^/]") + i += 1 + else: + regex.append(re.escape(resolved_pattern[i])) + i += 1 + + return re.fullmatch("".join(regex), target) is not None + + def load_rules(paths): rules, errors = [], [] for path in paths: @@ -311,29 +491,103 @@ def default_settings_paths(): ] -def _first_match(rules, kind, command): +def _first_match(rules, kind, command, tool="Bash"): for rule in rules: - if rule.kind == kind and rule.pattern is not None and pattern_matches(rule.pattern, command): + if rule.kind != kind or rule.tool != tool or rule.pattern is None: + continue + + if tool == "Bash": + matched = pattern_matches(rule.pattern, command) + else: + matched = path_pattern_matches( + rule.pattern, + command, + kind, + source=rule.source, + ) + + if matched: return rule + return None -def _match_with_env_forms(rules, kind, text): +def _match_with_env_forms(rules, kind, text, tool="Bash"): """Check the command as written first, then with its env prefix stripped. - A rule can name a prefix itself (`Bash(NODE_ENV=production npm publish *)`), - so stripping may only add matches, never remove them. Allow strips only - known-safe variables; deny and ask strip any assignment. + A rule can name a prefix itself, so stripping may only add matches. """ - stripped = strip_wrappers(text, env="safe" if kind == "allow" else "all") + stripped = strip_wrappers( + text, + env="safe" if kind == "allow" else "all", + ) + for form in dict.fromkeys((text, stripped)): - rule = _first_match(rules, kind, form) + rule = _first_match(rules, kind, form, tool=tool) if rule: return rule + return None -def explain(command, rules): +def explain(command, rules, tool="Bash"): + if tool not in {"Bash", "Read", "Edit"}: + raise ValueError( + f"Unsupported tool: {tool!r}. Expected Bash, Read, or Edit." + ) + + if tool != "Bash": + item = Subcommand(command) + + for kind, label in ( + ("deny", "deny"), + ("ask", "ask"), + ("allow", "allow"), + ): + rule = _first_match( + rules, + kind, + command, + tool=tool, + ) + + if rule: + item.decision = label + item.rule = rule.text + item.source = rule.source + break + + if item.decision == "deny": + return Explanation( + command, + "deny", + "A subcommand matches a deny rule.", + [item], + ) + + if item.decision == "ask": + return Explanation( + command, + "ask", + "A subcommand matches an ask rule.", + [item], + ) + + if item.decision == "allow": + return Explanation( + command, + "allow", + "Every subcommand matches an allow rule.", + [item], + ) + + return Explanation( + command, + "prompt", + "No allow rule matches the file path.", + [item], + ) + top, nested, parseable = split_command(command) subcommands = [] for text, is_nested in [(c, False) for c in top] + [(c, True) for c in nested]: @@ -379,7 +633,7 @@ def lint(rules): if key in seen: add("PW002", f"Duplicate of the same rule in {seen[key]}.") seen.setdefault(key, rule.source) - if rule.pattern is None: + if rule.tool != "Bash" or rule.pattern is None: continue pattern = rule.pattern @@ -460,7 +714,16 @@ def main(argv=None): output.add_argument("--json", action="store_true", help="print JSON") output.add_argument("--sarif", action="store_true", help="print SARIF 2.1.0 (lint only)") commands = parser.add_subparsers(dest="action", required=True) - explain_parser = commands.add_parser("explain", help="explain the decision for a command") + explain_parser = commands.add_parser( + "explain", + help="explain the decision for a command", + ) + explain_parser.add_argument( + "--tool", + choices=("Bash", "Read", "Edit"), + default="Bash", + help="permission tool to evaluate (default: Bash)", + ) explain_parser.add_argument("shell_command") commands.add_parser("lint", help="find ineffective or risky rules") args = parser.parse_args(argv) @@ -475,7 +738,11 @@ def main(argv=None): return 2 if args.action == "explain": - result = explain(args.shell_command, rules) + result = explain( + args.shell_command, + rules, + tool=args.tool, + ) if args.json: print(json.dumps(asdict(result), indent=2)) else: diff --git a/tests/test_permwhy.py b/tests/test_permwhy.py index ac310f5..88346c3 100644 --- a/tests/test_permwhy.py +++ b/tests/test_permwhy.py @@ -21,6 +21,149 @@ def rules(allow=(), ask=(), deny=()): return result +class PathPatternTest(unittest.TestCase): + def test_home_relative_path_pattern(self): + home = Path.home() + cwd = Path("C:/project") + + self.assertTrue( + permwhy.path_pattern_matches( + "~/.ssh/**", + str(home / ".ssh" / "config"), + "allow", + cwd=cwd, + ) + ) + + def test_filesystem_absolute_path_pattern(self): + cwd = Path("C:/project") + + self.assertTrue( + permwhy.path_pattern_matches( + "//**/.env", + "D:/project/.env", + "deny", + cwd=cwd, + ) + ) + + def test_source_relative_path_uses_project_root(self): + cwd = Path("C:/project") + source = "C:/project/.claude/settings.json" + + self.assertTrue( + permwhy.path_pattern_matches( + "/src/**", + "C:/project/src/main.py", + "allow", + source=source, + cwd=cwd, + ) + ) + + self.assertFalse( + permwhy.path_pattern_matches( + "/src/**", + "C:/other/src/main.py", + "allow", + source=source, + cwd=cwd, + ) + ) + + def test_custom_settings_source_relative_path(self): + cwd = Path("C:/project") + source = "C:/custom/settings.json" + + self.assertTrue( + permwhy.path_pattern_matches( + "/src/**", + "C:/custom/src/main.py", + "allow", + source=source, + cwd=cwd, + ) + ) + + self.assertFalse( + permwhy.path_pattern_matches( + "/src/**", + "C:/project/src/main.py", + "allow", + source=source, + cwd=cwd, + ) + ) + + def test_windows_drive_absolute_pattern(self): + cwd = Path("C:/project") + + self.assertTrue( + permwhy.path_pattern_matches( + "D:/project/secrets/**", + "D:/project/secrets/key.txt", + "deny", + cwd=cwd, + ) + ) + + def test_user_settings_source_relative_path(self): + cwd = Path("C:/project") + source = str(Path.home() / ".claude" / "settings.json") + home = Path.home() + + self.assertTrue( + permwhy.path_pattern_matches( + "/projects/**", + str(home / ".claude" / "projects" / "config.json"), + "allow", + source=source, + cwd=cwd, + ) + ) + + + def test_windows_paths_are_case_insensitive(self): + self.assertTrue( + permwhy.path_pattern_matches( + "C:/PROJECT/SRC/**", + "c:/project/src/Main.py", + "allow", + cwd="C:/project", + ) + ) + + def test_windows_paths_normalize_dot_segments(self): + self.assertTrue( + permwhy.path_pattern_matches( + "C:/project/src/**", + "c:/project/tmp/../src/./main.py", + "allow", + cwd="C:/project", + ) + ) + + def test_unc_paths_are_normalized(self): + self.assertTrue( + permwhy.path_pattern_matches( + r"\\\\server\\share\\src\\**", + r"\\\\SERVER\\SHARE\\src\\main.py", + "allow", + cwd="C:/project", + ) + ) + + def test_posix_paths_remain_case_sensitive(self): + self.assertFalse( + permwhy.path_pattern_matches( + "/project/src/**", + "/project/SRC/main.py", + "allow", + cwd="/project", + ) + ) + + class SplitCommandTest(unittest.TestCase): def test_every_documented_separator(self): top, _, parseable = permwhy.split_command("a && b || c ; d | e |& f & g\nh") @@ -95,7 +238,7 @@ def test_other_env_prefix_is_kept_for_allow(self): "--flag=x npm test", ): self.assertEqual(permwhy.strip_wrappers(command), command, command) - + def test_env_after_wrapper_is_not_a_prefix(self): # nohup is stripped, but an assignment after it is not a prefix any more self.assertEqual( @@ -184,7 +327,7 @@ def test_deny_matches_past_any_env_prefix(self): deny = rules(deny=["Bash(rm *)"]) self.assertEqual(permwhy.explain("FOO=bar rm -rf tmp/", deny).decision, "deny") self.assertEqual(permwhy.explain('echo "$(FOO=bar rm x)"', deny).decision, "deny") - + def test_deny_matches_past_env_prefix_with_expanded_value(self): deny = rules(deny=["Bash(rm *)"]) self.assertEqual(permwhy.explain("FOO=$(whoami) rm -rf x", deny).decision, "deny") @@ -192,7 +335,7 @@ def test_deny_matches_past_env_prefix_with_expanded_value(self): def test_ask_matches_past_any_env_prefix_in_chain(self): result = permwhy.explain("FOO=bar git push && npm test", rules(ask=["Bash(git push *)"])) self.assertEqual(result.decision, "ask") - + def test_escaped_space_cannot_hide_a_denied_command(self): both = rules(allow=["Bash(git *)"], deny=["Bash(rm *)"]) self.assertEqual(permwhy.explain(r"LANG=a\ git rm -rf x", both).decision, "deny") @@ -217,7 +360,7 @@ def test_deny_rule_on_a_bare_prefix_still_matches(self): def test_allow_rule_that_names_an_env_prefix_still_matches(self): allow = rules(allow=["Bash(NODE_ENV=test npm test)"]) self.assertEqual(permwhy.explain("NODE_ENV=test npm test", allow).decision, "allow") - + def test_redirection_in_env_value_is_not_approved_by_allow(self): allow = rules(allow=["Bash(npm test)"]) for command in ( @@ -231,8 +374,101 @@ def test_deny_matches_past_env_value_with_redirection(self): deny = rules(deny=["Bash(rm *)"]) self.assertEqual(permwhy.explain("FOO=x>f rm -rf x", deny).decision, "deny") - def test_non_bash_rules_are_ignored(self): - self.assertEqual(permwhy.explain("ls", rules(allow=["Read(./*)"])).decision, "prompt") + def test_read_allow_rule_matches_file_path(self): + result = permwhy.explain( + "./src/main.py", + rules(allow=["Read(./src/**)"]), + tool="Read", + ) + self.assertEqual(result.decision, "allow") + + def test_edit_allow_rule_matches_file_path(self): + result = permwhy.explain( + "./src/main.py", + rules(allow=["Edit(./src/**)"]), + tool="Edit", + ) + self.assertEqual(result.decision, "allow") + + def test_read_rule_does_not_match_edit_tool(self): + result = permwhy.explain( + "./src/main.py", + rules(allow=["Read(./src/**)"]), + tool="Edit", + ) + self.assertEqual(result.decision, "prompt") + + def test_deny_beats_allow_for_read_tool(self): + result = permwhy.explain( + "./src/main.py", + rules( + allow=["Read(./src/**)"], + deny=["Read(./src/main.py)"], + ), + tool="Read", + ) + self.assertEqual(result.decision, "deny") + + def test_ask_beats_allow_for_read_tool(self): + result = permwhy.explain( + "./src/main.py", + rules( + allow=["Read(./src/**)"], + ask=["Read(./src/main.py)"], + ), + tool="Read", + ) + self.assertEqual(result.decision, "ask") + + def test_read_single_star_does_not_match_nested_path(self): + result = permwhy.explain( + "src/utils/main.py", + rules(allow=["Read(src/*.py)"]), + tool="Read", + ) + self.assertEqual(result.decision, "prompt") + + def test_read_double_star_matches_direct_and_nested_paths(self): + allow = rules(allow=["Read(src/**/*.py)"]) + + direct = permwhy.explain("src/main.py", allow, tool="Read") + nested = permwhy.explain("src/utils/main.py", allow, tool="Read") + + self.assertEqual(direct.decision, "allow") + self.assertEqual(nested.decision, "allow") + + def test_src_double_star_has_same_rooting_for_all_rule_kinds(self): + cases = ( + ("allow", "allow"), + ("deny", "deny"), + ("ask", "ask"), + ) + + for kind, expected in cases: + with self.subTest(kind=kind): + rule_set = rules( + **{kind: ["Read(src/**)"]} + ) + + direct = permwhy.explain( + "src/main.py", + rule_set, + tool="Read", + ) + nested = permwhy.explain( + "src/utils/main.py", + rule_set, + tool="Read", + ) + elsewhere = permwhy.explain( + "packages/app/src/main.py", + rule_set, + tool="Read", + ) + + self.assertEqual(direct.decision, expected) + self.assertEqual(nested.decision, expected) + self.assertEqual(elsewhere.decision, "prompt") class LintTest(unittest.TestCase): @@ -280,6 +516,39 @@ def test_explain_json(self): self.assertEqual(code, 0) self.assertEqual(json.loads(output)["decision"], "allow") + def test_explain_read_tool(self): + code, output = self.run_cli( + '{"permissions":{"allow":["Read(./src/**)"]}}', + "--json", "explain", "--tool", "Read", "./src/main.py", + ) + self.assertEqual(code, 0) + self.assertEqual(json.loads(output)["decision"], "allow") + + + def test_explain_edit_tool(self): + code, output = self.run_cli( + '{"permissions":{"allow":["Edit(./src/**)"]}}', + "--json", "explain", "--tool", "Edit", "./src/main.py", + ) + self.assertEqual(code, 0) + self.assertEqual(json.loads(output)["decision"], "allow") + + def test_explain_function_rejects_invalid_tool(self): + with self.assertRaises(ValueError): + permwhy.explain( + "./src/main.py", + [], + tool="Write", + ) + + def test_explain_rejects_invalid_tool(self): + with self.assertRaises(SystemExit) as error: + self.run_cli( + '{"permissions":{}}', + "--json", "explain", "--tool", "Write", "./src/main.py", + ) + self.assertEqual(error.exception.code, 2) + def test_lint_exit_codes(self): self.assertEqual(self.run_cli('{"permissions":{"allow":["Bash(*)"]}}', "lint")[0], 1) self.assertEqual(self.run_cli('{"permissions":{"allow":["Bash(ls)"]}}', "lint")[0], 0)