Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 12 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,24 @@ 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

`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.
Expand All @@ -76,7 +78,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
Expand Down
3 changes: 2 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
@@ -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
4 changes: 2 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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.

Expand Down
54 changes: 50 additions & 4 deletions plugin/scripts/permwhy.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@
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"})
# 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
Expand Down Expand Up @@ -186,10 +195,32 @@ 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_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: dynamic values and redirections 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)
Expand Down Expand Up @@ -225,7 +256,7 @@ def strip_wrappers(command):
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() :]
Expand Down Expand Up @@ -287,14 +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)
# 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 = _match_with_env_forms(rules, kind, text)
if rule:
item.decision, item.rule, item.source = label, rule.text, rule.source
break
Expand Down
117 changes: 117 additions & 0 deletions tests/test_permwhy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"))

Expand Down Expand Up @@ -69,6 +70,62 @@ 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 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",
}
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=x>~/.bashrc npm test", # redirection in the value
"LANG=C>f npm test",
"NODE_ENV=x<in npm test",
"GOARCH=arm64 npm test", # not named in the docs
"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)

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):
self.assertTrue(permwhy.pattern_matches("ls *", "ls -la"))
Expand Down Expand Up @@ -114,6 +171,66 @@ 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_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_redirection_in_env_value_is_not_approved_by_allow(self):
allow = rules(allow=["Bash(npm test)"])
for command in (
"NODE_ENV=x>~/.bashrc npm test",
"LANG=C>f npm test",
"NODE_ENV=x<in npm test",
):
self.assertEqual(permwhy.explain(command, allow).decision, "prompt", command)

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")

Expand Down