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..d163e68 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 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..752bf25 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. 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 e940665..227201e 100644 --- a/plugin/scripts/permwhy.py +++ b/plugin/scripts/permwhy.py @@ -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 @@ -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) @@ -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() :] @@ -287,6 +318,21 @@ 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 = [] @@ -294,7 +340,7 @@ def explain(command, rules): 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 diff --git a/tests/test_permwhy.py b/tests/test_permwhy.py index 3334c1d..ac310f5 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,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~/.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")