Refuse a Read, Grep or Bash call that reads ~/.claude/.env or a config's env-file
CI / tests (pull_request) Failing after 2m29s
CI / tests (pull_request) Failing after 2m29s
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
"""Whether a Read, Grep or Bash call reads a credentials file, for the `env-file-read` rule.
|
||||
|
||||
The files are `~/.claude/.env` and every config's `env-file`, not only the calling project's: a worker in one client's project must not read another client's credentials either, and listing them needs no git call.
|
||||
A Bash command reads one where its text spells the file's path, or one of its words names the file from the directory `cd` left the command in.
|
||||
This guards against an agent reading the file in passing, not against one that hides the path, such as behind a glob or a variable of its own."""
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from failure import Failure
|
||||
from rule_hook.call import Call, text
|
||||
from rule_hook.git import guarded_git
|
||||
from rule_hook.rules import Breach
|
||||
from command_lines.shell_command import resolved, simple_commands
|
||||
from project_config.settings import env_files
|
||||
|
||||
|
||||
def env_file_breaches(call: Call, home: str) -> list[Breach]:
|
||||
guarded = [pathlib.Path(home, ".claude", ".env"), *env_files(pathlib.Path(home))]
|
||||
read = [path for path in guarded if path.is_file() and reads(call, path, home)]
|
||||
return [Breach("env-file-read", f"the call reads {path}, whose credentials would land in the transcript", call.cwd) for path in read]
|
||||
|
||||
|
||||
def reads(call: Call, path: pathlib.Path, home: str) -> bool:
|
||||
if call.tool == "Read":
|
||||
return names(resolved(call.cwd, text(call.given, "file_path"), home), path)
|
||||
if call.tool == "Grep":
|
||||
searched = resolved(call.cwd, text(call.given, "path") or ".", home)
|
||||
return names(searched, path) or holds(searched, path) and not ignored(path)
|
||||
if call.tool == "Bash":
|
||||
command = text(call.given, "command")
|
||||
relative = os.path.relpath(path, home)
|
||||
spellings = "|".join(re.escape(spelling) for spelling in (str(path), *(f"{prefix}/{relative}" for prefix in ("~", "$HOME", "${HOME}"))))
|
||||
# Bounded on both sides, so a longer path that holds a spelling, such as ~/.claude/.envrc, is another file.
|
||||
spelt = re.search(rf"(?<![\w./~-])(?:{spellings})(?![\w.-])", command)
|
||||
named = (resolved(simple.directory, word, home) for simple in simple_commands(command, call.cwd, home) for word in simple.words)
|
||||
return spelt is not None or any(names(word, path) for word in named)
|
||||
return False
|
||||
|
||||
|
||||
def names(given: str, path: pathlib.Path) -> bool:
|
||||
"""Whether given leads to path, through any symlink."""
|
||||
try:
|
||||
return os.path.realpath(given) == os.path.realpath(path)
|
||||
except ValueError:
|
||||
# A word holding a NUL byte names no file.
|
||||
return False
|
||||
|
||||
|
||||
def holds(folder: str, path: pathlib.Path) -> bool:
|
||||
return pathlib.Path(os.path.realpath(path)).is_relative_to(os.path.realpath(folder))
|
||||
|
||||
|
||||
def ignored(path: pathlib.Path) -> bool:
|
||||
"""Whether the checkout holding path ignores it: Grep runs ripgrep, which skips such a file in a folder it searches."""
|
||||
return not isinstance(guarded_git(str(path.parent), "check-ignore", "--quiet", path.name), Failure)
|
||||
@@ -3,7 +3,7 @@
|
||||
usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin)
|
||||
rule-hook overrides (prints this chunk's overrides)
|
||||
|
||||
settings.json runs it before each Agent, Bash, Edit, MultiEdit, Read, Skill and Write call, in every session and
|
||||
settings.json runs it before each Agent, Bash, Edit, Grep, MultiEdit, Read, Skill and Write call, in every session and
|
||||
subagent. The rules:
|
||||
|
||||
{rules}
|
||||
@@ -44,6 +44,7 @@ from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
|
||||
from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
|
||||
from git_cli.git_command import commits
|
||||
from rule_hook.committed_files import committed_file_breaches
|
||||
from rule_hook.env_file import env_file_breaches
|
||||
from failure import Failure
|
||||
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
|
||||
from rule_hook.file_text import read
|
||||
@@ -86,9 +87,11 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
|
||||
return text(call.given, "args"), text(call.given, "skill"), skill_breaches(call, environ)
|
||||
if call.tool == "Bash":
|
||||
command = text(call.given, "command")
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home)
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home) + env_file_breaches(call, home)
|
||||
if call.tool == "Read":
|
||||
return "", text(call.given, "file_path"), read_breaches(call, home)
|
||||
return "", text(call.given, "file_path"), read_breaches(call, home) + env_file_breaches(call, home)
|
||||
if call.tool == "Grep":
|
||||
return "", text(call.given, "path"), env_file_breaches(call, home)
|
||||
path = text(call.given, "file_path")
|
||||
if call.tool not in FILE_TOOLS or not path:
|
||||
return None
|
||||
|
||||
@@ -11,7 +11,7 @@ from command_lines.shell_command import launched, Simple
|
||||
from review_rules.review_folder import REPORTS
|
||||
from command_lines.docker_command import unlimited
|
||||
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "env-file-read", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -35,6 +35,12 @@ RULES: dict[RuleName, Rule] = {
|
||||
"a container made with docker run or docker create has a memory limit and a swap limit, as large as its work needs, such as `--memory 4g --memory-swap 4g`, so a runaway container fails alone instead of starving the machine; a swap limit equal to the memory limit keeps it out of swap",
|
||||
"docker run, docker create, docker container run and docker container create, whether direct or through a launcher such as nice or timeout. One under run-heavy passes, as run-heavy's docker adds the limits on Linux, unless it names docker by its path, or changes or clears PATH, as env -i, sudo or doas do. A container a script or docker compose starts is not checked",
|
||||
),
|
||||
# A marker would let the credentials into the transcript all the same, so no marker waives it.
|
||||
"env-file-read": Rule(
|
||||
"an agent never reads ~/.claude/.env or a project's env-file, the file of credentials its config names, since a value it reads lands in its transcript, which loop-claude archives and the backups copy; a tool that needs a credential reads the file itself, and `project-config env-file` prints the file's path",
|
||||
"a Read of the file, a Grep of the file or of a folder that holds it where no checkout ignores it, and a Bash command that spells the file's path or names it from the directory `cd` left the command in, against ~/.claude/.env and the env-file of every config under ~/.claude-projects",
|
||||
overridable=False,
|
||||
),
|
||||
"ignorefile-sorted": Rule(
|
||||
"each block of an ignore file is sorted in code-point order, as LC_ALL=C sort does, since its order carries no meaning; where order matters, such as a re-include after its exclude, split the block with a blank line or a comment",
|
||||
"a .*ignore file; a block already unsorted before the edit is left alone",
|
||||
|
||||
@@ -18,7 +18,7 @@ from rule_hook.rules import blocks, Breach, check, command_breaches, file_breach
|
||||
from rule_hook.main import breaches_of
|
||||
from rule_hook.call import Call, parsed_call
|
||||
from git_cli.git_command import commit_message, CommitCall, commits
|
||||
from project_config.test_project_config import configured
|
||||
from project_config.test_project_config import configured, write_config
|
||||
from release_plan.test_ranking import DECISIONS, README, TODO
|
||||
from rule_hook.git import guarded_git
|
||||
from test_env import isolated_env
|
||||
@@ -360,6 +360,53 @@ class ReviewerRung(unittest.TestCase):
|
||||
self.assertTrue(any("Skill" in tools for tools in matchers))
|
||||
|
||||
|
||||
class EnvFileRead(unittest.TestCase):
|
||||
"""A home with ~/.claude/.env and a config whose env-file lies outside any checkout."""
|
||||
def setUp(self) -> None:
|
||||
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
(self.home / ".claude").mkdir()
|
||||
(self.home / ".claude" / ".env").write_text("TOKEN=x\n")
|
||||
write_config(self.home, self.home / "code" / "acme")
|
||||
config = self.home / ".claude-projects" / "acme" / "config.toml"
|
||||
config.write_text(config.read_text() + 'env-file = "~/secrets/acme.env"\n')
|
||||
(self.home / "secrets").mkdir()
|
||||
(self.home / "secrets" / "acme.env").write_text("TOKEN=y\n")
|
||||
|
||||
def breached(self, tool: str, given: dict[str, typing.Any], cwd: str = "/r") -> list[str]:
|
||||
found = breaches_of(Call(tool, given, cwd), str(self.home), {})
|
||||
return sorted({rule for rule in rules(found[2]) if rule == "env-file-read"}) if found else []
|
||||
|
||||
def test_a_read_of_claude_s_env_or_a_config_s_env_file_is_refused(self):
|
||||
self.assertEqual(self.breached("Read", {"file_path": f"{self.home}/.claude/.env"}), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Read", {"file_path": "acme.env"}, f"{self.home}/secrets"), ["env-file-read"])
|
||||
|
||||
def test_a_read_through_a_symlink_is_refused(self):
|
||||
(self.home / "link").symlink_to(self.home / "secrets" / "acme.env")
|
||||
self.assertEqual(self.breached("Read", {"file_path": f"{self.home}/link"}), ["env-file-read"])
|
||||
|
||||
def test_a_read_of_another_file_passes(self):
|
||||
self.assertEqual(self.breached("Read", {"file_path": f"{self.home}/.claude/settings.json"}), [])
|
||||
|
||||
def test_a_grep_of_the_file_or_of_a_folder_holding_it_is_refused(self):
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/secrets/acme.env"}), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": str(self.home)}), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN"}, f"{self.home}/secrets"), ["env-file-read"])
|
||||
|
||||
def test_a_grep_of_a_folder_whose_checkout_ignores_the_file_or_of_another_folder_passes(self):
|
||||
subprocess.run(["git", "init", "--quiet", str(self.home / ".claude")], check=True, env=isolated_env())
|
||||
(self.home / ".claude" / ".gitignore").write_text(".env\n")
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/.claude"}), [])
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/code"}), [])
|
||||
|
||||
def test_a_command_naming_the_file_is_refused(self):
|
||||
for command in ("cat ~/.claude/.env", f"grep TOKEN {self.home}/secrets/acme.env", "source $HOME/secrets/acme.env", "wc < ${HOME}/.claude/.env", "cd ~/secrets && cat acme.env"):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), ["env-file-read"])
|
||||
|
||||
def test_a_command_naming_another_file_passes(self):
|
||||
self.assertEqual(self.breached("Bash", {"command": f"cat ~/.claude/.envrc /backup{self.home}/.claude/.env .env"}, "/r"), [])
|
||||
|
||||
|
||||
class ReviewerReport(unittest.TestCase):
|
||||
def breached(self, tool: str, path: str, agent: str = "prose-reviewer", cwd: str = "/r") -> list[str]:
|
||||
given = {"file_path": path, "content": "BLOCK\n"} if tool == "Write" else {"file_path": path, "old_string": "a", "new_string": "b"}
|
||||
|
||||
Reference in New Issue
Block a user