From 53586b48a3eb592a1e2ab508b1254b206bcfd10f Mon Sep 17 00:00:00 2001 From: FrundlesTian <92493187+FrundlesTian@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:38:00 +0800 Subject: [PATCH] fix: enforce CLAUDE_ALLOWED_TOOLS with a PreToolUse hook (#221) A tool left off CLAUDE_ALLOWED_TOOLS was not blocked: it fell through to the can_use_tool callback, which allowed it. Moving the check into that callback is not enough either -- a live session shows the CLI never consults it for calls that need no permission (read-only tools such as CronList, Task/Agent, reads inside the working directory). Enforce the list with a PreToolUse hook instead, which the CLI runs for every call, sub-agents' included. The hook denies unlisted tools and returns no decision for listed ones, so can_use_tool and its boundary checks still run. Tools of MCP servers in MCP_CONFIG_PATH are allowed when ENABLE_MCP=true, Task/Agent are aliases, scoped rules allow their base tool, and DISABLE_TOOL_VALIDATION=true turns the hook off. The CLI reports hook denials in permission_denials, so they reach the user. The default list gains TaskStop, BashOutput and KillShell, and settings.py, .env.example, docs/configuration.md and docs/tools.md now agree on it (20 tools). Verified against a live session (bundled CLI 2.1.277, ENABLE_MCP=true): CronList denied in the main thread and inside a sub-agent and reported in permission_denials; Agent, Read inside the sub-agent and an MCP tool still ran; can_use_tool still consulted with the hook in place. Co-Authored-By: Claude Opus 5.5 --- .env.example | 5 +- CLAUDE.md | 4 +- SECURITY.md | 19 +- docs/configuration.md | 2 +- docs/tools.md | 47 ++++- src/bot/orchestrator.py | 3 + src/claude/sdk_integration.py | 126 ++++++++++++ src/config/settings.py | 9 +- .../unit/test_claude/test_sdk_integration.py | 189 ++++++++++++++++++ 9 files changed, 384 insertions(+), 20 deletions(-) diff --git a/.env.example b/.env.example index fec147dd6..678fdfa9c 100644 --- a/.env.example +++ b/.env.example @@ -91,8 +91,9 @@ CLAUDE_MAX_COST_PER_USER=10.0 # Maximum cost per individual request in USD (SDK-level hard cap) CLAUDE_MAX_COST_PER_REQUEST=5.0 -# Allowed Claude tools (comma-separated list) -CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch,Skill,AskUserQuestion,EnterPlanMode,ExitPlanMode +# Allowed Claude tools (comma-separated list). Enforced: a tool not listed is +# denied. Tools of servers in MCP_CONFIG_PATH are allowed when ENABLE_MCP=true. +CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,TaskStop,BashOutput,KillShell,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch,Skill # === RATE LIMITING === # Number of requests allowed per window diff --git a/CLAUDE.md b/CLAUDE.md index c7b24d168..6582403d1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -88,9 +88,9 @@ context.bot_data["security_validator"] The `can_use_tool` callback (`src/claude/sdk_integration.py`) validates Claude's own tool calls *before* they execute: file paths for `Read`/`Write`/`Edit`/`MultiEdit`/`NotebookEdit`/`NotebookRead` against `APPROVED_DIRECTORY`, and `Bash` commands against the directory boundary. -The SDK consults this callback only when the Claude CLI sends a `can_use_tool` control request, and the CLI resolves allow rules first -- so a tool named in `CLAUDE_ALLOWED_TOOLS` is pre-approved and never reaches the callback. `ClaudeSDKManager.execute_command` therefore strips those guarded tools (`GUARDED_TOOLS`) from the `allowed_tools` it passes to the SDK, and sets `autoAllowBashIfSandboxed` to `False`, whenever a `SecurityValidator` is wired. Without this the checks are silently inert (issue #219). Removing a guarded tool from `CLAUDE_ALLOWED_TOOLS` does not disable it -- the callback allows anything that passes validation. +The SDK consults this callback only when the Claude CLI sends a `can_use_tool` control request, and the CLI resolves allow rules first -- so a tool named in `CLAUDE_ALLOWED_TOOLS` is pre-approved and never reaches the callback. `ClaudeSDKManager.execute_command` therefore strips those guarded tools (`GUARDED_TOOLS`) from the `allowed_tools` it passes to the SDK, and sets `autoAllowBashIfSandboxed` to `False`, whenever a `SecurityValidator` is wired. Without this the checks are silently inert (issue #219). `CLAUDE_ALLOWED_TOOLS` is enforced by a `PreToolUse` hook (`_make_tool_allowlist_hook`, issue #221), not by the callback: the CLI skips `can_use_tool` for calls that need no permission (read-only tools, `Task`/`Agent`, reads inside cwd), while hooks see every call, sub-agents' included. The hook denies unlisted tools, so removing a tool (guarded or not) disables it, and returns no decision for listed ones -- never `allow`, which would skip `can_use_tool`. Tools of MCP servers in `MCP_CONFIG_PATH` are allowed when `ENABLE_MCP=true`; `Task`/`Agent` are aliases. Unlisted tools, including ones a new CLI adds, fail closed. -`DISABLE_TOOL_VALIDATION=true` restores the fully permissive behaviour: no `allowed_tools`/`disallowed_tools` are sent, guarded tools are not routed through the callback, and sandboxed Bash is auto-approved. Trusted environments only. +`DISABLE_TOOL_VALIDATION=true` restores the fully permissive behaviour: no `allowed_tools`/`disallowed_tools` are sent, guarded tools are not routed through the callback, the allowlist is not enforced, and sandboxed Bash is auto-approved. Trusted environments only. Optional interactive approval layer: when `INTERACTIVE_TOOL_APPROVAL=true`, tool calls matching `INTERACTIVE_TOOL_APPROVAL_TOOLS` (default `Bash,Write,Edit`) additionally require the user to click Allow/Deny on a Telegram inline keyboard before executing, after the static checks above pass. If the user doesn't respond within `INTERACTIVE_TOOL_APPROVAL_TIMEOUT_SECONDS` (default 60), `INTERACTIVE_TOOL_APPROVAL_TIMEOUT_ACTION` (default `deny`, fail closed; can be set to `allow`) decides the outcome. The SDK's `can_use_tool` hook is only consulted for tools *not* already present in `allowed_tools` (a listed tool is pre-approved by the CLI and never reaches the callback), so gated tools are automatically removed from the `allowed_tools` sent to the SDK while this is enabled. diff --git a/SECURITY.md b/SECURITY.md index 5172869b6..c138f205f 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -97,10 +97,21 @@ bot) and `DISABLE_TOOL_VALIDATION` is `false` (the default). - Direct use of `ClaudeSDKManager` without a `SecurityValidator` (there is no validator to consult). -Note that `CLAUDE_ALLOWED_TOOLS` is not itself an enforcement boundary while the -callback is wired: a tool left out of the list is not blocked, it is simply routed -to the callback, which allows anything that passes the boundary checks. Use -`CLAUDE_DISALLOWED_TOOLS` to actually block a tool. +`CLAUDE_ALLOWED_TOOLS` is enforced by a separate `PreToolUse` hook, which the CLI +runs for every tool call -- sub-agents' calls included. The callback cannot do +this job: the CLI does not consult it for calls that need no permission +(read-only tools, sub-agent launches, reads inside the working directory). The +hook denies a tool that is not on the list, so a filesystem tool removed from the +list is disabled outright; for a listed tool it makes no decision, leaving the +call to the allow rules and the callback above (a hook "allow" would skip the +callback). Tools of the MCP servers in `MCP_CONFIG_PATH` are allowed when +`ENABLE_MCP=true`. A tool nobody listed, including one a future CLI introduces, +is denied: the list is the single source of truth, and the CLI reports each +denial in the run result, which the bot shows in its reply. Before this was +fixed, a tool left off the list was allowed +([#221](https://github.com/overwirehq/claude-code-telegram/issues/221)). The hook +is off under `DISABLE_TOOL_VALIDATION=true`. `CLAUDE_DISALLOWED_TOOLS` still +blocks a tool even when it is listed. **Known gap:** token-based authentication is not usable end to end. The provider exists, but `src/main.py` still backs it with `InMemoryTokenStorage`, so issued diff --git a/docs/configuration.md b/docs/configuration.md index ecd91207f..62482ec4c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -94,7 +94,7 @@ CLAUDE_MAX_COST_PER_USER=10.0 CLAUDE_MAX_COST_PER_REQUEST=5.0 # Allowed Claude tools (comma-separated list; see docs/tools.md for descriptions) -CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch +CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,TaskStop,BashOutput,KillShell,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch,Skill ``` #### Rate Limiting diff --git a/docs/tools.md b/docs/tools.md index 6267abbba..1ea2219c0 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -4,7 +4,7 @@ This document describes the tools that Claude Code can use when interacting thro ## Overview -By default, the bot allows **16 tools**, configured via the `CLAUDE_ALLOWED_TOOLS` environment variable. Tool calls that touch the filesystem are validated before they run by the `can_use_tool` callback in [`src/claude/sdk_integration.py`](../src/claude/sdk_integration.py), which checks file paths and Bash commands against the `APPROVED_DIRECTORY`. +By default, the bot allows **20 tools**, configured via the `CLAUDE_ALLOWED_TOOLS` environment variable. The list is enforced: a tool that is not on it is denied before it runs. The default includes names used by older Claude CLI versions (`Glob`, `Grep`, `LS`, `BashOutput`, `KillShell`, ...) so that it works across versions; a listed tool the CLI does not have is simply never called. Tool calls that touch the filesystem are validated before they run by the `can_use_tool` callback in [`src/claude/sdk_integration.py`](../src/claude/sdk_integration.py), which checks file paths and Bash commands against the `APPROVED_DIRECTORY`. When Claude uses a tool during a conversation, the tool name appears in real-time if verbose output is enabled (`/verbose 1` or `/verbose 2`). A tool call that fails a boundary check is denied before it executes, and Claude is told why. @@ -58,8 +58,17 @@ When Claude uses a tool during a conversation, the tool name appears in real-tim | Tool | Icon | Description | |------|------|-------------| -| **Task** | 🧠 | Launch a sub-agent to handle complex, multi-step operations autonomously. The sub-agent runs with its own context and returns a result when finished. | +| **Task** | 🧠 | Launch a sub-agent to handle complex, multi-step operations autonomously. The sub-agent runs with its own context and returns a result when finished. Newer CLIs call this tool **Agent**; either name in the list allows both. Sub-agent tool calls are checked against the same list. | | **TaskOutput** | 🧠 | Read the output of a background sub-agent launched by **Task**. Required for retrieving results from agents that were run in the background. | +| **TaskStop** | 🧠 | Stop a running background task or shell. | +| **BashOutput** | 💻 | Read the output of a background shell (older CLI versions). | +| **KillShell** | 💻 | Stop a background shell (older CLI versions; newer ones use **TaskStop**). | + +### Extensions + +| Tool | Icon | Description | +|------|------|-------------| +| **Skill** | 🔧 | Run a skill defined for the project. | ## Verbose Output @@ -92,17 +101,34 @@ The default allowed tools list is defined in `src/config/settings.py` and can be ```bash # Allow only specific tools (comma-separated) -CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch +CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,TaskStop,BashOutput,KillShell,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch,Skill # Explicitly block specific tools (comma-separated, takes precedence over allowed) CLAUDE_DISALLOWED_TOOLS=Bash,Write ``` -`CLAUDE_DISALLOWED_TOOLS` is the list that actually blocks a tool. `CLAUDE_ALLOWED_TOOLS` -pre-approves tools so they skip the permission handler; the filesystem tools are -deliberately withheld from that pre-approval so their boundary checks run (see -[Security](../SECURITY.md#tool-call-enforcement)), which means dropping one of them -from the list does not disable it. +A tool that is not in `CLAUDE_ALLOWED_TOOLS` is denied, and the reply tells you +which calls were blocked. Removing a tool from the list disables it -- the +filesystem tools included, although they are withheld from the CLI's +pre-approval so their boundary checks run (see +[Security](../SECURITY.md#tool-call-enforcement)). + +Things to know when trimming or extending the list: + +- **MCP tools** (`mcp____`): with `ENABLE_MCP=true`, every tool of a + server in `MCP_CONFIG_PATH` is allowed. MCP servers from anywhere else (such as + a project's `.mcp.json`) are denied unless listed, by tool name or as + `mcp__` for the whole server. +- **Tools left out on purpose:** `AskUserQuestion`, `EnterPlanMode` and + `ExitPlanMode` need an interactive Claude Code UI that the bot does not have, + and newer CLI tools that schedule work, run commands in the background or spawn + agents (`Monitor`, `CronCreate`, `Workflow`, `SendMessage`, ...) are not in the + default list. Add one to the list to opt in. +- **New CLI tools** are denied until listed. If a CLI upgrade introduces a tool + you want, add it to the list. +- An empty `CLAUDE_ALLOWED_TOOLS` means no allowlist, not "allow nothing". + +`CLAUDE_DISALLOWED_TOOLS` blocks a tool even if it is in the allowed list. To turn off tool validation entirely: @@ -124,7 +150,8 @@ Even when a tool is allowed, additional security checks apply. The exact checks 4. **Audit logging** (all modes) — All tool calls and security violations are recorded for review. -Layers 1 and 3 require `DISABLE_TOOL_VALIDATION=false` (the default); setting it to -`true` disables them along with the allow/deny lists. +Layers 1 and 3, and enforcement of `CLAUDE_ALLOWED_TOOLS`, require +`DISABLE_TOOL_VALIDATION=false` (the default); setting it to `true` disables them +along with the allow/deny lists. See [Security](../SECURITY.md) for the full security model. diff --git a/src/bot/orchestrator.py b/src/bot/orchestrator.py index 5801772e5..b3d72e724 100644 --- a/src/bot/orchestrator.py +++ b/src/bot/orchestrator.py @@ -104,6 +104,9 @@ def _redact_secrets(text: str) -> str: "LS": "\U0001f4c2", "Task": "\U0001f9e0", "TaskOutput": "\U0001f9e0", + "TaskStop": "\U0001f9e0", + "BashOutput": "\U0001f4bb", + "KillShell": "\U0001f4bb", "WebFetch": "\U0001f310", "WebSearch": "\U0001f310", "NotebookRead": "\U0001f4d3", diff --git a/src/claude/sdk_integration.py b/src/claude/sdk_integration.py index c67b16f85..ed5058bf4 100644 --- a/src/claude/sdk_integration.py +++ b/src/claude/sdk_integration.py @@ -2,6 +2,7 @@ import asyncio import os +import re from dataclasses import dataclass, field from pathlib import Path from typing import ( @@ -11,6 +12,7 @@ Callable, Dict, FrozenSet, + Iterable, List, Optional, ) @@ -24,6 +26,10 @@ CLIConnectionError, CLIJSONDecodeError, CLINotFoundError, + HookContext, + HookInput, + HookJSONOutput, + HookMatcher, Message, PermissionResultAllow, PermissionResultDeny, @@ -286,6 +292,102 @@ def _to_int(value: Any) -> Optional[int]: # Keys under which the guarded file tools pass their target path. _FILE_PATH_KEYS = ("file_path", "path", "notebook_path") +# Tools the CLI has renamed. An allowlist entry under either name covers calls +# under the other, so a CLAUDE_ALLOWED_TOOLS value written for one CLI version +# keeps sub-agents working on the next. +_TOOL_ALIASES = {"Agent": "Task", "Task": "Agent"} + +_MCP_PREFIX = "mcp__" + + +def _mcp_tool_prefix(server_name: str) -> str: + """Return the ``mcp____`` prefix the CLI gives a server's tools. + + The CLI replaces characters outside ``[a-zA-Z0-9_-]`` in the server name. + """ + return f"{_MCP_PREFIX}{re.sub(r'[^a-zA-Z0-9_-]', '_', server_name)}__" + + +def _make_tool_allowlist( + allowed_tools: Iterable[str], + mcp_server_names: Iterable[str] = (), +) -> Callable[[str], bool]: + """Build a predicate telling whether a tool name is on the allowlist. + + ``allowed_tools`` uses the CLI's allow-rule syntax. Plain names match + exactly; ``mcp__`` and ``mcp____*`` cover every tool of + that server. A scoped rule such as ``Bash(git:*)`` allows the tool by + name: the hook runs before the CLI's allow rules and cannot evaluate the + scope, so calls outside it are left to the CLI and can_use_tool. Every + tool of a configured MCP server (``mcp_server_names``) is allowed, since + MCP tool names are never listed in CLAUDE_ALLOWED_TOOLS. See issue #221. + """ + names = set() + prefixes = [_mcp_tool_prefix(server) for server in mcp_server_names] + for entry in allowed_tools: + entry = entry.split("(", 1)[0].strip() + if not entry: + continue + if entry.startswith(_MCP_PREFIX): + server_rule = entry[: -len("__*")] if entry.endswith("__*") else entry + if "__" not in server_rule[len(_MCP_PREFIX) :]: + prefixes.append(server_rule + "__") + continue + names.add(entry) + + def is_allowed(tool_name: str) -> bool: + if tool_name in names or _TOOL_ALIASES.get(tool_name) in names: + return True + return any(tool_name.startswith(prefix) for prefix in prefixes) + + return is_allowed + + +def _make_tool_allowlist_hook(is_allowed: Callable[[str], bool]) -> Any: + """Create a PreToolUse hook that denies tools not on the allowlist. + + This cannot live in can_use_tool: the CLI consults that callback only for + calls that need permission, and runs read-only tools, sub-agent launches + and reads inside the working directory without asking. A PreToolUse hook + sees every call, sub-agents' included. Allowed calls get an empty result, + never ``permissionDecision: "allow"``, which would skip can_use_tool and + with it the boundary checks. The CLI reports a denied call in the + result's ``permission_denials``, which the bot shows the user. See issue + #221. + """ + + async def pre_tool_use( + input_data: HookInput, + tool_use_id: Optional[str], + context: HookContext, + ) -> HookJSONOutput: + if input_data["hook_event_name"] != "PreToolUse": + return {} + tool_name = input_data["tool_name"] + if is_allowed(tool_name): + return {} + + # Fails closed: a tool nobody listed -- including one a newer CLI + # introduces -- is denied. + logger.warning( + "Denied tool not in CLAUDE_ALLOWED_TOOLS", + tool_name=tool_name, + agent_type=input_data.get("agent_type"), + ) + return { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": ( + f"The {tool_name} tool is not enabled for this bot " + "(it is not in CLAUDE_ALLOWED_TOOLS). Do not retry it; " + "continue without it or tell the user it is unavailable." + ), + } + } + + return pre_tool_use + def _make_can_use_tool_callback( security_validator: SecurityValidator, @@ -540,6 +642,30 @@ def _stderr_callback(line: str) -> None: mcp_config_path=str(self.config.mcp_config_path), ) + # Enforce CLAUDE_ALLOWED_TOOLS (#221). Built from the configured + # list, not sdk_allowed_tools: the guarded and approval-gated tools + # stripped above are still allowed, they just have to pass + # can_use_tool. An unset or empty list sends the CLI no allow + # rules, so it is read as "no allowlist" rather than "allow + # nothing". + if ( + not self.config.disable_tool_validation + and self.config.claude_allowed_tools + ): + tool_allowlist = _make_tool_allowlist( + self.config.claude_allowed_tools, + mcp_server_names=( + options.mcp_servers + if isinstance(options.mcp_servers, dict) + else () + ), + ) + options.hooks = { + "PreToolUse": [ + HookMatcher(hooks=[_make_tool_allowlist_hook(tool_allowlist)]) + ] + } + # Wire can_use_tool callback for preventive tool validation if self.security_validator: options.can_use_tool = _make_can_use_tool_callback( diff --git a/src/config/settings.py b/src/config/settings.py index 9802ada43..779176d03 100644 --- a/src/config/settings.py +++ b/src/config/settings.py @@ -119,6 +119,10 @@ class Settings(BaseSettings): # docs/configuration.md, .env.example, # src/claude/facade.py (_get_admin_instructions), # and src/bot/orchestrator.py (_TOOL_ICONS). + # This is enforced: a tool not on it is denied (#221). It names tools from + # older CLI versions too (Glob, Grep, LS, BashOutput, KillShell, ...) so + # the default works across versions; listing a tool the CLI lacks is + # harmless. claude_allowed_tools: Optional[List[str]] = Field( default=[ "Read", @@ -130,6 +134,9 @@ class Settings(BaseSettings): "LS", "Task", "TaskOutput", + "TaskStop", + "BashOutput", + "KillShell", "MultiEdit", "NotebookRead", "NotebookEdit", @@ -139,7 +146,7 @@ class Settings(BaseSettings): "WebSearch", "Skill", ], - description="List of allowed Claude tools", + description="List of allowed Claude tools; tools not listed are denied", ) claude_disallowed_tools: Optional[List[str]] = Field( default=[], diff --git a/tests/unit/test_claude/test_sdk_integration.py b/tests/unit/test_claude/test_sdk_integration.py index 5c81dadc2..580a1eb38 100644 --- a/tests/unit/test_claude/test_sdk_integration.py +++ b/tests/unit/test_claude/test_sdk_integration.py @@ -25,6 +25,8 @@ ClaudeSDKManager, StreamUpdate, _make_can_use_tool_callback, + _make_tool_allowlist, + _make_tool_allowlist_hook, ) from src.config.settings import Settings @@ -1494,6 +1496,193 @@ async def test_config_allowed_tools_not_mutated(self, tmp_path): assert config.claude_allowed_tools == original +class TestToolAllowlist: + """CLAUDE_ALLOWED_TOOLS is enforced by a PreToolUse hook (#221). + + Before #221 a tool left off the list fell through to can_use_tool, which + allowed it -- and tools the CLI runs without asking (read-only tools, + sub-agent launches) never reached the callback at all. + """ + + def test_plain_names_match_exactly(self): + allowed = _make_tool_allowlist(["Read", "Grep"]) + assert allowed("Read") + assert allowed("Grep") + assert not allowed("WebFetch") + assert not allowed("read") + + def test_task_and_agent_are_aliases(self): + """The CLI renamed Task to Agent; either entry keeps sub-agents working.""" + assert _make_tool_allowlist(["Task"])("Agent") + assert _make_tool_allowlist(["Agent"])("Task") + + def test_scoped_rule_allows_the_tool_by_name(self): + """The hook runs before the CLI's allow rules and cannot evaluate + Bash(git:*); denying Bash would block the git calls it pre-approves.""" + allowed = _make_tool_allowlist(["Bash(git:*)"]) + assert allowed("Bash") + assert not allowed("Read") + + def test_configured_mcp_servers_are_allowed(self): + allowed = _make_tool_allowlist(["Read"], mcp_server_names=["github"]) + assert allowed("mcp__github__create_issue") + assert not allowed("mcp__other__tool") + assert not allowed("mcp__githubx__tool") + + def test_mcp_server_name_is_normalised(self): + """The CLI replaces characters outside [a-zA-Z0-9_-] in server names.""" + allowed = _make_tool_allowlist([], mcp_server_names=["my.server"]) + assert allowed("mcp__my_server__tool") + + @pytest.mark.parametrize("entry", ["mcp__github", "mcp__github__*"]) + def test_server_level_mcp_rules(self, entry): + allowed = _make_tool_allowlist([entry]) + assert allowed("mcp__github__create_issue") + assert not allowed("mcp__gitlab__create_issue") + + def test_single_mcp_tool_rule(self): + allowed = _make_tool_allowlist(["mcp__github__create_issue"]) + assert allowed("mcp__github__create_issue") + assert not allowed("mcp__github__delete_repo") + + # -- the PreToolUse hook ------------------------------------------------ + + @staticmethod + def _hook_input(tool_name, tool_input=None, **extra): + return { + "hook_event_name": "PreToolUse", + "tool_name": tool_name, + "tool_input": tool_input or {}, + "tool_use_id": "toolu_1", + "session_id": "s", + "transcript_path": "/t", + "cwd": "/c", + **extra, + } + + async def test_hook_denies_unlisted_tool(self): + hook = _make_tool_allowlist_hook(_make_tool_allowlist(["Read"])) + out = await hook(self._hook_input("CronList"), "toolu_1", {"signal": None}) + decision = out["hookSpecificOutput"] + assert decision["hookEventName"] == "PreToolUse" + assert decision["permissionDecision"] == "deny" + assert "CronList" in decision["permissionDecisionReason"] + assert "CLAUDE_ALLOWED_TOOLS" in decision["permissionDecisionReason"] + + async def test_hook_denies_unlisted_tool_inside_subagent(self): + hook = _make_tool_allowlist_hook(_make_tool_allowlist(["Read", "Task"])) + out = await hook( + self._hook_input("CronList", agent_id="a1", agent_type="general-purpose"), + "toolu_1", + {"signal": None}, + ) + assert out["hookSpecificOutput"]["permissionDecision"] == "deny" + + async def test_hook_makes_no_decision_for_listed_tool(self): + """An explicit "allow" would skip can_use_tool and its boundary checks.""" + hook = _make_tool_allowlist_hook(_make_tool_allowlist(["Write"])) + out = await hook( + self._hook_input("Write", {"file_path": "/etc/passwd"}), + "toolu_1", + {"signal": None}, + ) + assert out == {} + + async def test_hook_ignores_other_events(self): + hook = _make_tool_allowlist_hook(_make_tool_allowlist([])) + out = await hook( + {**self._hook_input("CronList"), "hook_event_name": "PostToolUse"}, + "toolu_1", + {"signal": None}, + ) + assert out == {} + + # -- wiring through execute_command ------------------------------------ + + @staticmethod + async def _options(tmp_path, validator=None, **overrides): + settings = Settings( + telegram_bot_token="test:token", + telegram_bot_username="testbot", + approved_directory=tmp_path, + claude_timeout_seconds=2, + **overrides, + ) + manager = ClaudeSDKManager(settings, security_validator=validator) + return await TestGuardedToolsNotPreApproved._capture(manager, tmp_path) + + @classmethod + async def _decide(cls, options, tool_name, tool_input=None): + """Run the configured PreToolUse hooks; True if the call may proceed.""" + for matcher in (options.hooks or {}).get("PreToolUse", []): + for hook in matcher.hooks: + out = await hook( + cls._hook_input(tool_name, tool_input), "toolu_1", {"signal": None} + ) + decision = out.get("hookSpecificOutput", {}).get("permissionDecision") + assert decision != "allow", "would bypass can_use_tool" + if decision == "deny": + return False + return True + + async def test_default_config_denies_unlisted_tool(self, tmp_path): + options = await self._options( + tmp_path, TestGuardedToolsNotPreApproved._validator(tmp_path) + ) + assert not await self._decide(options, "CronList") + assert not await self._decide(options, "Workflow") + # Stripped from allowed_tools, but still on the allowlist. + assert await self._decide(options, "Bash", {"command": "ls"}) + assert await self._decide(options, "Read", {"file_path": "x"}) + # Sub-agents, under either tool name. + assert await self._decide(options, "Task") + assert await self._decide(options, "Agent") + + async def test_removed_guarded_tool_is_denied(self, tmp_path): + options = await self._options( + tmp_path, + TestGuardedToolsNotPreApproved._validator(tmp_path), + claude_allowed_tools=["Read", "Grep"], + ) + assert not await self._decide(options, "Write", {"file_path": "a.txt"}) + assert not await self._decide(options, "Bash", {"command": "ls"}) + assert await self._decide(options, "Read", {"file_path": "a.txt"}) + + async def test_disable_tool_validation_skips_enforcement(self, tmp_path): + options = await self._options( + tmp_path, + TestGuardedToolsNotPreApproved._validator(tmp_path), + disable_tool_validation=True, + ) + assert not options.hooks + assert await self._decide(options, "Workflow") + + async def test_empty_allowlist_is_not_enforced(self, tmp_path): + """An empty list sends no allow rules; it is "unset", not "allow nothing".""" + options = await self._options( + tmp_path, + TestGuardedToolsNotPreApproved._validator(tmp_path), + claude_allowed_tools=[], + ) + assert await self._decide(options, "Workflow") + + async def test_mcp_config_servers_allowed(self, tmp_path): + import json + + mcp_config = tmp_path / "mcp.json" + mcp_config.write_text( + json.dumps({"mcpServers": {"github": {"command": "gh-mcp"}}}) + ) + options = await self._options( + tmp_path, + TestGuardedToolsNotPreApproved._validator(tmp_path), + enable_mcp=True, + mcp_config_path=mcp_config, + ) + assert await self._decide(options, "mcp__github__list_prs") + assert not await self._decide(options, "mcp__rogue__tool") + + class TestSessionIdFallback: """Test fallback session ID extraction from StreamEvent messages."""