From c37727dc51f745c14696a6a12ebe5f0a335e6859 Mon Sep 17 00:00:00 2001 From: Mohammadjavadfakhri Date: Sat, 31 Oct 2026 18:59:31 +0330 Subject: [PATCH 1/4] Strip documented env-var prefixes before matching Bash rules --- plugin/scripts/permwhy.py | 32 ++++++++++++++++-- tests/test_permwhy.py | 68 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 2 deletions(-) diff --git a/plugin/scripts/permwhy.py b/plugin/scripts/permwhy.py index e940665..7714186 100644 --- a/plugin/scripts/permwhy.py +++ b/plugin/scripts/permwhy.py @@ -24,6 +24,11 @@ RUNNERS = ("npx", "docker exec", "docker run", "devbox run", "uv run", "pnpm dlx", "uvx") PACKAGE_RUNS = ("npm run", "pnpm run", "yarn run", "bun run", "make") RULE_PATTERN = re.compile(r"^([A-Za-z][A-Za-z0-9_]*)(?:\((.*)\))?$", re.DOTALL) +ENV_ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=") +# Claude Code does not publish the full list of "known-safe" variables. +# These are the ones its docs name in examples; extend only with evidence. +SAFE_ENV_VARS = frozenset({"NODE_ENV", "LANG", "NO_COLOR", "GOARCH"}) +RAW_WORD = re.compile(r"(?:[^\s'\"]+|'[^']*'|\"(?:[^\"\\]|\\.)*\")+") @dataclass @@ -189,7 +194,29 @@ def _normalize(subcommand): return strip_wrappers(" ".join(words)) -def strip_wrappers(command): +def _strip_env_prefix(command, env): + """Drop leading NAME=value words. env: "safe" (allow rules), "all" (deny/ask), "none".""" + if env == "none": + return command + count = 0 + for word in RAW_WORD.findall(command): + match = ENV_ASSIGNMENT.match(word) + if not match: + break + name, value = word[: match.end() - 1], word[match.end() :] + if env == "safe" and any(char in value for char in "$`("): + break # allow side: a dynamic value can't be judged statically + if env == "safe" and name not in SAFE_ENV_VARS: + break + count += 1 + if count == 0: + return command + rest = _drop_words(command, count).strip() + return rest or command # a bare assignment stays as written + + +def strip_wrappers(command, env="safe"): + command = _strip_env_prefix(command, env) while True: try: words = shlex.split(command) @@ -292,9 +319,10 @@ def explain(command, rules): subcommands = [] for text, is_nested in [(c, False) for c in top] + [(c, True) for c in nested]: item = Subcommand(text, nested=is_nested) + strict = strip_wrappers(text, env="all") # deny/ask see past any env prefix # Docs: deny, then ask, then allow. Rule specificity doesn't change the order. for kind, label in (("deny", "deny"), ("ask", "ask"), ("allow", "allow")): - rule = _first_match(rules, kind, text) + rule = _first_match(rules, kind, strict if kind != "allow" else text) if rule: item.decision, item.rule, item.source = label, rule.text, rule.source break diff --git a/tests/test_permwhy.py b/tests/test_permwhy.py index 3334c1d..86b6cce 100644 --- a/tests/test_permwhy.py +++ b/tests/test_permwhy.py @@ -7,6 +7,7 @@ from contextlib import redirect_stdout from pathlib import Path + ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "plugin" / "scripts")) @@ -69,6 +70,51 @@ def test_runners_are_not_stripped(self): self.assertEqual(permwhy.strip_wrappers("npx rm -rf x"), "npx rm -rf x") + def test_safe_env_prefix_is_stripped(self): + cases = { + "NODE_ENV=test npm test": "npm test", + "NODE_ENV=test GOARCH=arm64 npm test": "npm test", + 'NODE_ENV="a b" npm test': "npm test", + "NODE_ENV=test nohup npm test": "npm test", + } + for given, want in cases.items(): + self.assertEqual(permwhy.strip_wrappers(given), want, given) + + def test_other_env_prefix_is_kept_for_allow(self): + for command in ( + "FOO=bar npm test", + "NODE_ENV=$(whoami) npm test", # dynamic value + "NODE_ENV=`whoami` npm test", + "NODE_ENV=test", # bare assignment + "npm test --flag=x", + "--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( + permwhy.strip_wrappers("nohup NODE_ENV=test npm test"), + "NODE_ENV=test npm test", + ) + + def test_env_all_strips_any_assignment(self): + cases = { + "FOO=$HOME rm x": "rm x", + "FOO=$(whoami) rm x": "rm x", + "FOO=bar npm test": "npm test", + "A=1 B=2 npm test": "npm test", + "FOO=bar nohup npm test": "npm test", + "FOO=bar": "FOO=bar", + } + for given, want in cases.items(): + self.assertEqual(permwhy.strip_wrappers(given, env="all"), want, given) + + def test_env_none_keeps_prefix(self): + command = "NODE_ENV=test npm test" + self.assertEqual(permwhy.strip_wrappers(command, env="none"), command) + + class MatchTest(unittest.TestCase): def test_word_boundary(self): self.assertTrue(permwhy.pattern_matches("ls *", "ls -la")) @@ -114,6 +160,28 @@ def test_docs_example_deny_misses_other_invocations(self): def test_wrapper_is_stripped_before_matching(self): self.assertEqual(permwhy.explain("timeout 30 npm test", rules(allow=["Bash(npm test)"])).decision, "allow") + + def test_allow_matches_past_safe_env_prefix(self): + result = permwhy.explain("NODE_ENV=test npm test", rules(allow=["Bash(npm test *)"])) + self.assertEqual(result.decision, "allow") + + def test_allow_does_not_match_past_other_env_prefix(self): + result = permwhy.explain("FOO=bar npm test", rules(allow=["Bash(npm test *)"])) + self.assertEqual(result.decision, "prompt") + + 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") + + 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_non_bash_rules_are_ignored(self): self.assertEqual(permwhy.explain("ls", rules(allow=["Read(./*)"])).decision, "prompt") From ac229c81cf5bb7c997250ea5403d5cdc26c5b27d Mon Sep 17 00:00:00 2001 From: Mohammadjavadfakhri Date: Sun, 1 Nov 2026 18:12:03 +0330 Subject: [PATCH 2/4] Drop undocumented GOARCH; update changelog, README, roadmap and architecture docs --- CHANGELOG.md | 6 ++++++ README.md | 21 ++++++++++----------- ROADMAP.md | 3 ++- docs/architecture.md | 4 ++-- plugin/scripts/permwhy.py | 2 +- tests/test_permwhy.py | 4 +++- 6 files changed, 24 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a407096..ab1de92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,19 @@ All notable changes are documented here, in [Keep a Changelog](https://keepachan ## [Unreleased] +### Added + +- `explain` strips leading environment-variable assignments before matching: allow rules see past known-safe variables (`NODE_ENV`, `LANG`, `NO_COLOR`), deny and ask rules see past any assignment. + ## [0.1.0] - 2026-11-01 ### Changed + - Contributing guide and PR template state the PR rules - README covers common questions ### Added + - `lint` can emit SARIF 2.1.0 reports with stable descriptors for all finding codes. - `explain` shows the permission decision for each subcommand. - `lint` reports nine kinds of ineffective or risky rule. diff --git a/README.md b/README.md index f990320..81e22bd 100644 --- a/README.md +++ b/README.md @@ -50,17 +50,17 @@ Try both commands on the rules in `examples/settings.json`. $ python3 plugin/scripts/permwhy.py --settings examples/settings.json --sarif lint > permwhy.sarif -| Code | Finding | -|---|---| -| PW001 | Not a valid rule | -| PW002 | Duplicate rule | -| PW003 | Blanket Bash allow | -| PW004 | Wildcarded interpreter | -| PW005 | Wildcarded package-manager run | -| PW006 | Runner that matches whatever runs inside it | -| PW007 | Allow rule shadowed by a deny rule | +| Code | Finding | +| ----- | ----------------------------------------------- | +| PW001 | Not a valid rule | +| PW002 | Duplicate rule | +| PW003 | Blanket Bash allow | +| PW004 | Wildcarded interpreter | +| PW005 | Wildcarded package-manager run | +| PW006 | Runner that matches whatever runs inside it | +| PW007 | Allow rule shadowed by a deny rule | | PW008 | Deny or ask rule that only matches command text | -| PW009 | Fragile URL pattern | +| PW009 | Fragile URL pattern | ## Limits @@ -76,7 +76,6 @@ Try both commands on the rules in `examples/settings.json`. Contributions are welcome, from people and from people working with AI agents. See [CONTRIBUTING.md](CONTRIBUTING.md). Good first issues: -- Handle `FOO=bar command` environment prefixes - Explain `Read` and `Edit` rules as well as `Bash` - Add SARIF output so `lint` can report in GitHub code scanning - Support `PowerShell(...)` rules diff --git a/ROADMAP.md b/ROADMAP.md index c55dbda..5e25395 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,9 +1,10 @@ # Roadmap ## Next -- Environment variable prefixes in `explain` + - `Read` and `Edit` rule explanations ## Later + - `PowerShell(...)` rules - Suggest the narrowest rule for a prompted command diff --git a/docs/architecture.md b/docs/architecture.md index 29bfae9..78ec203 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,8 +5,8 @@ rules --> lint --> findings - **`split_command`** walks the text once, tracking quotes. It splits on the documented separators and collects commands nested in subshells, substitutions and control-flow bodies. -- **`strip_wrappers`** removes only the wrappers the docs list. -- **`explain`** checks deny, then ask, then allow. Nested commands can trigger deny and ask but don't need an allow. +- **`strip_wrappers`** removes the wrappers the docs list, and leading environment-variable assignments. For allow rules only known-safe variables are stripped; for deny and ask rules any assignment is. +- **`explain`** checks deny, then ask, then allow. Deny and ask look at each subcommand with any leading assignment stripped; allow looks at it with only known-safe ones stripped. Nested commands can trigger deny and ask but don't need an allow. - **`lint`** checks each rule against patterns the docs warn about. - **The skill** tells Claude to run the script instead of reasoning through the rules. diff --git a/plugin/scripts/permwhy.py b/plugin/scripts/permwhy.py index 7714186..b730fe0 100644 --- a/plugin/scripts/permwhy.py +++ b/plugin/scripts/permwhy.py @@ -27,7 +27,7 @@ ENV_ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=") # Claude Code does not publish the full list of "known-safe" variables. # These are the ones its docs name in examples; extend only with evidence. -SAFE_ENV_VARS = frozenset({"NODE_ENV", "LANG", "NO_COLOR", "GOARCH"}) +SAFE_ENV_VARS = frozenset({"NODE_ENV", "LANG", "NO_COLOR"}) RAW_WORD = re.compile(r"(?:[^\s'\"]+|'[^']*'|\"(?:[^\"\\]|\\.)*\")+") diff --git a/tests/test_permwhy.py b/tests/test_permwhy.py index 86b6cce..3a8ef8a 100644 --- a/tests/test_permwhy.py +++ b/tests/test_permwhy.py @@ -73,7 +73,8 @@ def test_runners_are_not_stripped(self): def test_safe_env_prefix_is_stripped(self): cases = { "NODE_ENV=test npm test": "npm test", - "NODE_ENV=test GOARCH=arm64 npm test": "npm test", + "NODE_ENV=test NO_COLOR=1 npm test": "npm test", + "LANG=C npm test": "npm test", 'NODE_ENV="a b" npm test': "npm test", "NODE_ENV=test nohup npm test": "npm test", } @@ -85,6 +86,7 @@ def test_other_env_prefix_is_kept_for_allow(self): "FOO=bar npm test", "NODE_ENV=$(whoami) npm test", # dynamic value "NODE_ENV=`whoami` npm test", + "GOARCH=arm64 npm test", # not named in the docs "NODE_ENV=test", # bare assignment "npm test --flag=x", "--flag=x npm test", From ab138c1aa1394a1a8e1b44d98048e83c3a62ed1d Mon Sep 17 00:00:00 2001 From: Mohammadjavadfakhri Date: Mon, 2 Nov 2026 15:24:37 +0330 Subject: [PATCH 3/4] Keep escaped spaces in env values; match rules against the command as written --- docs/architecture.md | 2 +- plugin/scripts/permwhy.py | 28 +++++++++++++++++++++++----- tests/test_permwhy.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 6 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 78ec203..752bf25 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -6,7 +6,7 @@ - **`split_command`** walks the text once, tracking quotes. It splits on the documented separators and collects commands nested in subshells, substitutions and control-flow bodies. - **`strip_wrappers`** removes the wrappers the docs list, and leading environment-variable assignments. For allow rules only known-safe variables are stripped; for deny and ask rules any assignment is. -- **`explain`** checks deny, then ask, then allow. Deny and ask look at each subcommand with any leading assignment stripped; allow looks at it with only known-safe ones stripped. Nested commands can trigger deny and ask but don't need an allow. +- **`explain`** checks deny, then ask, then allow. Each rule is checked against the subcommand as written and with leading environment assignments stripped (any assignment for deny and ask, known-safe ones for allow), so stripping only adds matches. Nested commands can trigger deny and ask but don't need an allow. - **`lint`** checks each rule against patterns the docs warn about. - **The skill** tells Claude to run the script instead of reasoning through the rules. diff --git a/plugin/scripts/permwhy.py b/plugin/scripts/permwhy.py index b730fe0..fb2e6bf 100644 --- a/plugin/scripts/permwhy.py +++ b/plugin/scripts/permwhy.py @@ -28,7 +28,11 @@ # Claude Code does not publish the full list of "known-safe" variables. # These are the ones its docs name in examples; extend only with evidence. SAFE_ENV_VARS = frozenset({"NODE_ENV", "LANG", "NO_COLOR"}) -RAW_WORD = re.compile(r"(?:[^\s'\"]+|'[^']*'|\"(?:[^\"\\]|\\.)*\")+") +# One shell word: plain characters, backslash-escaped characters (so `a\ b` +# stays one word), quoted strings, and a lone trailing backslash. +_WORD = r"(?:\\.|[^\s'\"\\]+|'[^']*'|\"(?:[^\"\\]|\\.)*\"|\\)+" +RAW_WORD = re.compile(_WORD, re.DOTALL) +WORD_AND_SPACE = re.compile(_WORD + r"\s*", re.DOTALL) @dataclass @@ -191,7 +195,7 @@ def _normalize(subcommand): words.pop(0) if not words or words[0] in TRAILING_ONLY or words[0] in ("for", "case"): return "" - return strip_wrappers(" ".join(words)) + return strip_wrappers(" ".join(words), env="none") def _strip_env_prefix(command, env): @@ -252,7 +256,7 @@ def strip_wrappers(command, env="safe"): def _drop_words(command, count): rest = command.lstrip() for _ in range(count): - match = re.match(r"(?:[^\s'\"]+|'[^']*'|\"(?:[^\"\\]|\\.)*\")+\s*", rest) + match = WORD_AND_SPACE.match(rest) if not match: return rest rest = rest[match.end() :] @@ -314,15 +318,29 @@ def _first_match(rules, kind, command): return None +def _match_with_env_forms(rules, kind, text): + """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. + """ + stripped = strip_wrappers(text, env="safe" if kind == "allow" else "all") + for form in dict.fromkeys((text, stripped)): + rule = _first_match(rules, kind, form) + if rule: + return rule + return None + + def explain(command, rules): top, nested, parseable = split_command(command) subcommands = [] for text, is_nested in [(c, False) for c in top] + [(c, True) for c in nested]: item = Subcommand(text, nested=is_nested) - strict = strip_wrappers(text, env="all") # deny/ask see past any env prefix # Docs: deny, then ask, then allow. Rule specificity doesn't change the order. for kind, label in (("deny", "deny"), ("ask", "ask"), ("allow", "allow")): - rule = _first_match(rules, kind, strict if kind != "allow" else text) + rule = _match_with_env_forms(rules, kind, text) if rule: item.decision, item.rule, item.source = label, rule.text, rule.source break diff --git a/tests/test_permwhy.py b/tests/test_permwhy.py index 3a8ef8a..4f19fca 100644 --- a/tests/test_permwhy.py +++ b/tests/test_permwhy.py @@ -116,6 +116,12 @@ def test_env_none_keeps_prefix(self): command = "NODE_ENV=test npm test" self.assertEqual(permwhy.strip_wrappers(command, env="none"), command) + def test_escaped_space_stays_inside_the_assignment_value(self): + # The shell runs `rm -rf x` with LANG="a git". + self.assertEqual(permwhy.strip_wrappers(r"LANG=a\ git rm -rf x"), "rm -rf x") + self.assertEqual(permwhy.strip_wrappers(r"FOO=a\ b rm -rf x", env="all"), "rm -rf x") + # FOO is not a safe variable, so the allow side leaves it alone. + self.assertEqual(permwhy.strip_wrappers(r"FOO=a\ b rm -rf x"), r"FOO=a\ b rm -rf x") class MatchTest(unittest.TestCase): def test_word_boundary(self): @@ -183,6 +189,31 @@ 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") + self.assertEqual(permwhy.explain(r"FOO=a\ b rm -rf x", both).decision, "deny") + allow_only = rules(allow=["Bash(git *)"]) + self.assertEqual(permwhy.explain(r"LANG=a\ git rm -rf x", allow_only).decision, "prompt") + + def test_deny_rule_that_names_an_env_prefix_still_matches(self): + command = "NODE_ENV=production npm publish --tag x" + deny = rules(allow=["Bash(npm publish *)"], deny=["Bash(NODE_ENV=production npm publish *)"]) + self.assertEqual(permwhy.explain(command, deny).decision, "deny") + + def test_ask_rule_that_names_an_env_prefix_still_matches(self): + command = "NODE_ENV=production npm publish --tag x" + ask = rules(allow=["Bash(npm publish *)"], ask=["Bash(NODE_ENV=production npm publish *)"]) + self.assertEqual(permwhy.explain(command, ask).decision, "ask") + + def test_deny_rule_on_a_bare_prefix_still_matches(self): + both = rules(allow=["Bash(git *)"], deny=["Bash(FOO=bar *)"]) + self.assertEqual(permwhy.explain("FOO=bar git status", both).decision, "deny") + + 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_non_bash_rules_are_ignored(self): self.assertEqual(permwhy.explain("ls", rules(allow=["Read(./*)"])).decision, "prompt") From 800367e1b94834911481ac8fb809c6ea806e652a Mon Sep 17 00:00:00 2001 From: Mohammadjavadfakhri Date: Tue, 3 Nov 2026 11:58:50 +0330 Subject: [PATCH 4/4] Refuse redirections in allow-side env values; document the shell-parsing limit --- README.md | 2 ++ plugin/scripts/permwhy.py | 4 ++-- tests/test_permwhy.py | 16 ++++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 81e22bd..d163e68 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,8 @@ Try both commands on the rules in `examples/settings.json`. `permwhy` follows [Claude Code's documented permission behavior](https://code.claude.com/docs/en/permissions), but it is a separate approximation, so Claude Code has the final say. It doesn't know Claude Code's built-in read-only list, managed settings, or auto mode's classifier decisions. Permission rules also aren't a security boundary: use a sandbox for that. +It doesn't parse shell syntax in full. For example, an expanded value that contains spaces in a leading assignment, such as `FOO=$(echo a) rm -rf x`, isn't split correctly, so a deny rule like `Bash(rm *)` doesn't match it and `explain` returns `prompt` even though Claude Code's docs say deny rules match past any leading assignment. + ## FAQ **Why does Claude Code keep asking for permission?** Often one part of a compound command has no matching rule. `permwhy explain` shows the decision for each part. diff --git a/plugin/scripts/permwhy.py b/plugin/scripts/permwhy.py index fb2e6bf..227201e 100644 --- a/plugin/scripts/permwhy.py +++ b/plugin/scripts/permwhy.py @@ -208,8 +208,8 @@ def _strip_env_prefix(command, env): if not match: break name, value = word[: match.end() - 1], word[match.end() :] - if env == "safe" and any(char in value for char in "$`("): - break # allow side: a dynamic value can't be judged statically + if env == "safe" and any(char in value for char in "$`(<>"): + break # allow side: dynamic values and redirections can't be judged statically if env == "safe" and name not in SAFE_ENV_VARS: break count += 1 diff --git a/tests/test_permwhy.py b/tests/test_permwhy.py index 4f19fca..ac310f5 100644 --- a/tests/test_permwhy.py +++ b/tests/test_permwhy.py @@ -86,6 +86,9 @@ def test_other_env_prefix_is_kept_for_allow(self): "FOO=bar npm test", "NODE_ENV=$(whoami) npm test", # dynamic value "NODE_ENV=`whoami` npm test", + "NODE_ENV=x>~/.bashrc npm test", # redirection in the value + "LANG=C>f npm test", + "NODE_ENV=x~/.bashrc npm test", + "LANG=C>f npm test", + "NODE_ENV=xf rm -rf x", deny).decision, "deny") def test_non_bash_rules_are_ignored(self): self.assertEqual(permwhy.explain("ls", rules(allow=["Read(./*)"])).decision, "prompt")