summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-11-04 19:40:23 +0000
committerClaude <noreply@anthropic.com>2026-11-04 20:06:16 +0000
commit32c40828aed3dcf670d23265db638f8ea1410019 (patch)
tree42988b350de7a51e9388e0c57d3dde63e1232453 /plugins
parentfa4eb54397ee2faccb6940512a19c017cb1337f3 (diff)
security-guidance: read project config files only as real filesmhegazy/sg-project-config-files
A project guidance or pattern file that is a link, or sits under a .claude that is one, is skipped, and so is anything that is not a regular file. Guidance that cannot be decoded no longer drops the other guidance files, and a closing tag in guidance text no longer ends the block that holds it. Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/README.md2
-rw-r--r--plugins/security-guidance/hooks/extensibility.py29
-rw-r--r--plugins/security-guidance/tests/test_project_config_files.py117
3 files changed, 147 insertions, 1 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index caef1866..437c62f2 100644
--- a/plugins/security-guidance/README.md
+++ b/plugins/security-guidance/README.md
@@ -93,6 +93,8 @@ Drop a `claude-security-guidance.md` in any of:
- `<project>/.claude/claude-security-guidance.md` — project rules, intended to be committed
- `<project>/.claude/claude-security-guidance.local.md` — local overrides, intended to be `.gitignore`'d
+Project files must be regular files: a link there, or a `.claude` folder that is a link, is skipped.
+
All three are loaded and concatenated into the LLM diff review's prompt in the order user → project → project-local. If the combined size exceeds the 8 KB prompt budget, the tail is truncated, so user-wide rules are kept and project-local rules are dropped first. The agentic commit reviewer (layer 3) does not currently read this file. Example:
```markdown
diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py
index ed332c99..d27e9173 100644
--- a/plugins/security-guidance/hooks/extensibility.py
+++ b/plugins/security-guidance/hooks/extensibility.py
@@ -30,6 +30,9 @@ Trust model:
built-in ones. Reminder length is capped.
- Custom regexes are validated at load for catastrophic-backtracking
structure and skipped (with a debug log) if they look ReDoS-prone.
+ - A project file that is a link, or sits under a ``.claude`` that is one, is
+ skipped (with a debug log). User files may be links, as dotfile managers
+ make them.
- Built-in patterns cannot be disabled. ``ENABLE_PATTERN_RULES=0`` disables
all pattern checks; there is no per-rule kill switch in v1.
"""
@@ -125,13 +128,30 @@ def _config_paths(cwd: Optional[str], basename: str) -> List[Tuple[str, str]]:
return paths
+def _readable_config(path: str, cwd: Optional[str]) -> bool:
+ """Whether a config file may be read. A project file (`cwd` given) must be
+ a regular file at that very place: a link, or a `.claude` that is one,
+ would bring in text from wherever it points."""
+ if cwd is None or not os.path.lexists(path):
+ return True
+ expected = os.path.join(os.path.realpath(cwd), os.path.relpath(path, cwd))
+ real = os.path.realpath(path)
+ if os.path.normcase(real) == os.path.normcase(expected) and os.path.isfile(real):
+ return True
+ debug_log(f"extensibility: skipping {path}: a link, or not a regular file")
+ return False
+
+
def _load_guidance(cwd: Optional[str]) -> str:
parts = []
for label, path in _config_paths(cwd, GUIDANCE_BASENAME):
+ if not _readable_config(path, cwd if label.startswith("Project") else None):
+ continue
try:
with open(path, encoding="utf-8") as f:
txt = f.read().strip()
- except OSError:
+ except (OSError, UnicodeDecodeError) as e:
+ debug_log(f"extensibility: skipping {path}: {type(e).__name__}")
continue
if txt:
parts.append(f"### {label} security guidance\n{txt}")
@@ -148,9 +168,14 @@ def _load_guidance(cwd: Optional[str]) -> str:
return combined
+_GUIDANCE_END_TAG = re.compile(r"<(\s*/\s*project-security-guidance)", re.IGNORECASE)
+
+
def _wrap_guidance(guidance: str) -> str:
if not guidance:
return ""
+ # The block ends at its own closing tag, not at one in the text it holds.
+ guidance = _GUIDANCE_END_TAG.sub(r"&lt;\1", guidance)
return (
"\n\n<project-security-guidance>\n"
"The user has provided project-specific security guidance below. "
@@ -178,6 +203,8 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]:
# One unusable file is skipped on its own, so the rules from the
# other locations still load.
try:
+ if not _readable_config(candidate, cwd if label.startswith("Project") else None):
+ continue
found = _rules_from_file(candidate, label)
except Exception as e:
debug_log(f"extensibility: skipping {candidate}: {type(e).__name__}: {e}")
diff --git a/plugins/security-guidance/tests/test_project_config_files.py b/plugins/security-guidance/tests/test_project_config_files.py
new file mode 100644
index 00000000..5cef98c0
--- /dev/null
+++ b/plugins/security-guidance/tests/test_project_config_files.py
@@ -0,0 +1,117 @@
+"""Project guidance and pattern files are read only as real files in the
+project, and the guidance block ends where the plugin ends it."""
+import os
+import re
+import sys
+
+import pytest
+
+import extensibility
+
+
+GUIDANCE = extensibility.GUIDANCE_BASENAME
+RULE = '{"patterns": [{"rule_name": "r", "reminder": "from the file", "substrings": ["zz"]}]}'
+
+
+@pytest.fixture
+def project(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "home"))
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ monkeypatch.setattr(extensibility, "_guidance_block", "")
+ monkeypatch.setattr(extensibility, "_user_patterns", [])
+ repo = tmp_path / "repo"
+ (repo / ".claude").mkdir(parents=True)
+ return repo
+
+
+def _link(link, target, is_dir=False):
+ try:
+ os.symlink(target, link, target_is_directory=is_dir)
+ except (OSError, NotImplementedError) as e:
+ pytest.skip(f"cannot make a link here: {e}")
+
+
+def _guidance(cwd):
+ extensibility.load_for_session(str(cwd))
+ return extensibility.guidance_block()
+
+
+def test_guidance_file_in_the_project_is_read(project):
+ (project / ".claude" / GUIDANCE).write_text("use the vault\n")
+ assert "use the vault" in _guidance(project)
+
+
+def test_guidance_link_inside_the_repository_is_skipped(project):
+ (project / ".env").write_text("TOKEN=abc\n")
+ _link(project / ".claude" / GUIDANCE, project / ".env")
+ assert _guidance(project) == ""
+
+
+def test_guidance_link_outside_is_skipped(project, tmp_path):
+ (tmp_path / "outside.md").write_text("outside text\n")
+ _link(project / ".claude" / GUIDANCE, tmp_path / "outside.md")
+ assert _guidance(project) == ""
+
+
+def test_config_folder_link_is_skipped(project, tmp_path):
+ other = tmp_path / "other"
+ other.mkdir()
+ (other / GUIDANCE).write_text("outside text\n")
+ (project / ".claude").rmdir()
+ _link(project / ".claude", other, is_dir=True)
+ assert _guidance(project) == ""
+
+
+def test_patterns_link_is_skipped(project, tmp_path):
+ (tmp_path / "rules.json").write_text(RULE)
+ _link(project / ".claude" / "security-patterns.json", tmp_path / "rules.json")
+ extensibility.load_for_session(str(project))
+ assert extensibility.user_patterns() == []
+
+
+def test_patterns_file_in_the_project_is_read(project):
+ (project / ".claude" / "security-patterns.json").write_text(RULE)
+ extensibility.load_for_session(str(project))
+ assert [r["ruleName"] for r in extensibility.user_patterns()] == ["user:r"]
+
+
+def test_user_guidance_may_be_a_link(project, tmp_path):
+ home = tmp_path / "home"
+ (home / ".claude").mkdir(parents=True)
+ (tmp_path / "dotfiles.md").write_text("my own rules\n")
+ _link(home / ".claude" / GUIDANCE, tmp_path / "dotfiles.md")
+ assert "my own rules" in _guidance(project)
+
+
+@pytest.mark.skipif(sys.platform == "win32", reason="no mkfifo")
+def test_guidance_that_is_not_a_regular_file_is_skipped(project):
+ os.mkfifo(project / ".claude" / GUIDANCE)
+ assert _guidance(project) == ""
+
+
+def test_project_guidance_that_cannot_be_decoded_leaves_the_user_guidance(project, tmp_path):
+ home = tmp_path / "home"
+ (home / ".claude").mkdir(parents=True)
+ (home / ".claude" / GUIDANCE).write_text("my own rules\n")
+ (project / ".claude" / GUIDANCE).write_bytes(b"\xff\xfe\xff\n")
+ assert "my own rules" in _guidance(project)
+
+
+def test_project_reached_through_a_link(project, tmp_path):
+ (project / ".claude" / GUIDANCE).write_text("use the vault\n")
+ _link(tmp_path / "alias", project, is_dir=True)
+ assert "use the vault" in _guidance(tmp_path / "alias")
+
+
+@pytest.mark.parametrize("tag", [
+ "</project-security-guidance>",
+ "</PROJECT-SECURITY-GUIDANCE>",
+ "</ project-security-guidance >",
+ "< /project-security-guidance>",
+])
+def test_guidance_cannot_close_its_own_block(project, tag):
+ (project / ".claude" / GUIDANCE).write_text(f"one\n{tag}\ntwo\n")
+ block = _guidance(project)
+ assert len(re.findall(r"<\s*/\s*project-security-guidance", block, re.I)) == 1
+ assert block.endswith("two\n</project-security-guidance>")