summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-15 21:31:03 +0000
committerClaude <noreply@anthropic.com>2026-10-15 21:31:03 +0000
commit6788ec2df38bbbe81a86f8fca51b0ebb7bf0e558 (patch)
treec0b64c34a3800afd4d4374ed139289d9bfe91830
parent8f814f49002ff824e8a9ba43cf96112dc7f5948d (diff)
security-guidance: give the commit reviewer only read toolsmhegazy/sg-reviewer-read-only-tools
allowed_tools only pre-approves tools, so the inner Claude Code that runs a review was still offered the shell, file edits, web access and subagents. Pass the exact tool list instead: Read, Grep and Glob for the commit reviewer, none for the single-turn review.
-rw-r--r--plugins/security-guidance/hooks/llm.py42
-rw-r--r--plugins/security-guidance/tests/test_reviewer_tools.py84
2 files changed, 113 insertions, 13 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 3f7607c6..8ff97d6f 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -596,8 +596,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None)
3P providers. Uses the same `output_format` JSON-schema contract so the
return value shape is identical (parsed dict or None).
- No tools (`allowed_tools=[]`) — the security review only needs structured
- output, not Read/Grep/Glob. Single turn keeps cost predictable.
+ No tools (see _only_tools_args) — the security review only needs
+ structured output, not Read/Grep/Glob. Single turn keeps cost predictable.
"""
global _last_call_claude_http_error
_last_call_claude_http_error = None
@@ -645,6 +645,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None)
system_prompt=CLAUDE_CODE_SYSTEM_PROMPT,
cli_path=cli_path,
allowed_tools=[],
+ extra_args=_only_tools_args(),
setting_sources=[],
max_turns=2,
model=chosen_model,
@@ -1404,6 +1405,23 @@ def _send_sdk_logs_to_debug_log() -> None:
sdk_logger.propagate = False
+# The agentic reviewer reads a diff it must not trust, so it gets
+# file-reading tools and nothing else.
+_REVIEWER_TOOLS = ("Read", "Grep", "Glob")
+
+
+def _only_tools_args(tools: Tuple[str, ...] = ()) -> Dict[str, Optional[str]]:
+ """extra_args that make `tools` the inner CLI's whole tool set.
+
+ allowed_tools only pre-approves tools. Without these flags the inner CLI
+ still offers every Claude Code tool (shell, file edits, web, subagents)
+ and any configured MCP server, and whether a call to one runs is left to
+ the permission mode that CLI starts in. Passed as CLI flags because not
+ every Agent SDK build that can run a review has a `tools` option.
+ """
+ return {"tools": ",".join(tools), "strict-mcp-config": None}
+
+
def _agentic_spawn_env() -> Dict[str, str]:
"""opts.env for the SDK-spawned inner `claude` CLI.
@@ -1426,11 +1444,11 @@ def _agentic_spawn_env() -> Dict[str, str]:
"CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR": "",
"CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR": "",
"CLAUDE_CODE_INCLUDE_PARTIAL_MESSAGES": "",
- # Neutralize git config/env hijack vectors so an allowlisted
- # `git diff/log/show` cannot be turned into RCE via diff.external,
- # core.pager, core.sshCommand, or an inherited GIT_* var. The agentic
- # session only needs read-only history inspection; it never needs an
- # external diff driver, a pager, or a remote.
+ # Neutralize git config/env hijack vectors so a `git diff/log/show`
+ # cannot be turned into RCE via diff.external, core.pager,
+ # core.sshCommand, or an inherited GIT_* var. The inner CLI has no
+ # shell tool (see _only_tools_args); this stays as a second line of
+ # defence should it ever run git.
"GIT_CONFIG_NOSYSTEM": "1",
"GIT_CONFIG_GLOBAL": "/dev/null",
"GIT_EXTERNAL_DIFF": "",
@@ -1613,12 +1631,10 @@ def agentic_review(
system_prompt=system,
cwd=context_dir,
cli_path=cli_path,
- allowed_tools=["Read", "Grep", "Glob"],
- # Read/Grep/Glob within cwd are auto-approved in default
- # permission mode, so bypassPermissions is unnecessary (and
- # would trip our own agent-permission-bypass guidance). Leaving
- # permission_mode unset means an accidental future addition of
- # a write/exec tool to allowed_tools is caught by the gate.
+ # Pre-approved, and the only tools the reviewer has: no
+ # permission mode can then let it write, run or fetch anything.
+ allowed_tools=list(_REVIEWER_TOOLS),
+ extra_args=_only_tools_args(_REVIEWER_TOOLS),
setting_sources=[],
max_turns=turns if turns is not None else max_turns,
model=model,
diff --git a/plugins/security-guidance/tests/test_reviewer_tools.py b/plugins/security-guidance/tests/test_reviewer_tools.py
new file mode 100644
index 00000000..3e2aa86c
--- /dev/null
+++ b/plugins/security-guidance/tests/test_reviewer_tools.py
@@ -0,0 +1,84 @@
+"""The inner Claude Code the plugin starts for a review gets only the tools
+the review needs."""
+import sys
+import types
+
+import pytest
+
+import llm
+
+READ_ONLY = {"tools": "Read,Grep,Glob", "strict-mcp-config": None}
+NO_TOOLS = {"tools": "", "strict-mcp-config": None}
+
+
+def test_tool_flags():
+ assert llm._only_tools_args(("Read", "Grep", "Glob")) == READ_ONLY
+ assert llm._only_tools_args() == NO_TOOLS
+
+
+def test_flags_reach_the_command_line_of_the_installed_sdk():
+ sdk = pytest.importorskip("claude_agent_sdk")
+ transport = pytest.importorskip(
+ "claude_agent_sdk._internal.transport.subprocess_cli")
+ opts = sdk.ClaudeAgentOptions(
+ cli_path="claude", allowed_tools=["Read", "Grep", "Glob"],
+ extra_args=llm._only_tools_args(llm._REVIEWER_TOOLS))
+ cmd = transport.SubprocessCLITransport(prompt="x", options=opts)._build_command()
+ assert cmd[cmd.index("--tools") + 1] == "Read,Grep,Glob"
+ assert cmd.count("--tools") == 1 and "--strict-mcp-config" in cmd
+
+
+@pytest.fixture
+def sdk(monkeypatch, tmp_path):
+ """Stand-in for claude_agent_sdk that records each spawn's options. The
+ first agentic stage reports one finding, later stages keep it."""
+ spawned = []
+
+ class ClaudeAgentOptions:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+
+ class ResultMessage:
+ subtype, usage, total_cost_usd = "success", {}, 0.0
+
+ def __init__(self, structured_output):
+ self.structured_output = structured_output
+
+ async def query(prompt, options):
+ spawned.append(options.kwargs)
+ if len(spawned) == 1:
+ yield ResultMessage({"hasVulnerabilities": False, "vulnerabilities": [],
+ "findings": [{
+ "filePath": "a.py", "category": "c", "vulnerableCode": "x = 1",
+ "explanation": "e", "fix": "f", "severity": "high"}]})
+ else:
+ yield ResultMessage({"findings": [], "survived": [0]})
+
+ mod = types.ModuleType("claude_agent_sdk")
+ mod.ClaudeAgentOptions, mod.ResultMessage, mod.query = ClaudeAgentOptions, ResultMessage, query
+ mod.AssistantMessage = type("AssistantMessage", (), {})
+ monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "")
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state"))
+ for var in ("CONTEXT_DIR", "DEBUG_DIR", "MODEL", "ITER2", "FILTER", "NO_ADJUDICATE",
+ "DIFF_INTERSECT", "EXCLUDE_MEDIUM", "MAX_TURNS"):
+ monkeypatch.delenv("SG_AGENTIC_" + var, raising=False)
+ return spawned
+
+
+def test_every_agentic_stage_gets_only_the_read_tools(sdk, tmp_path):
+ _, vulns, _ = llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"])
+ assert len(vulns) == 1
+ # investigate, second investigate pass, refute
+ assert len(sdk) == 3
+ for opts in sdk:
+ assert opts["extra_args"] == READ_ONLY
+ assert opts["allowed_tools"] == ["Read", "Grep", "Glob"]
+ assert "permission_mode" not in opts
+
+
+def test_single_turn_sdk_review_gets_no_tools(sdk):
+ schema = {"type": "object", "properties": {}}
+ assert llm._call_claude_via_sdk("review this", schema) is not None
+ assert len(sdk) == 1
+ assert sdk[0]["extra_args"] == NO_TOOLS and sdk[0]["allowed_tools"] == []