Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

### Fixed
- **Scoped allow rules for guarded tools no longer bypass `can_use_tool`**: the strip that keeps guarded tools out of `allowed_tools` (#219) compared entries by exact name, so a scoped rule such as `Bash(git:*)`, `Read(//etc/**)` or `Write(*)` in `CLAUDE_ALLOWED_TOOLS` was passed to the CLI, which pre-approved every call it matched — the `APPROVED_DIRECTORY` and Bash boundary checks never ran, and neither did the interactive approval prompt for a tool in `INTERACTIVE_TOOL_APPROVAL_TOOLS`. Allow rules are now matched by the tool they name, the part before `(`, so a scoped rule is stripped whenever its tool is guarded or approval-gated. Matching calls reach the callback and are allowed only if they pass validation, so a rule written to narrow what Claude may do no longer removes a security layer (#244)
- **A run that stops early no longer reports success**: Claude produces no final text when the CLI kills a run at the turn limit, so the bot fell through to its "✅ Task completed" placeholder and told the user the work was done. A run that died at turn 10 mid-task and a run that finished were indistinguishable in Telegram (#172). `ResultMessage.subtype` is now read alongside the cost and session id, the placeholder claims completion only for `success`, and the reply carries a footer saying why the run ended — turn limit, cost budget, cancellation, or an unrecognised reason named by its raw subtype — with the turn count and a prompt to send another message to continue. Every place the bot renders a Claude reply carries it — typed messages, document, photo and voice input in agentic mode, the same four in classic mode, `/continue`, the Continue Session button and the quick-action buttons, whose `✅ … Complete` heading now reads `⚠️ … Stopped` when the run was cut short. Webhook-triggered and scheduled runs carry it too: nobody is watching those, so the reason a nightly job came back short is the whole of what its notification can say about it (#230)
- **`ClaudeResponse.num_turns` is the turn count the CLI reports**: it was derived by counting `UserMessage` and `AssistantMessage` objects, which over-reports — every tool result arrives as another user message — so a run stopped at turn 10 could be recorded as having taken roughly twice that. It only reached the logs and the session store before; the stop-reason footer now shows it to the user, which made the approximation worth removing. `ResultMessage.num_turns` is used where the CLI supplies it, with the message count kept as the fallback for a result that carries none
- **Inline code spans accept backtick runs of any length**: `markdown_to_telegram_html` matched a code span only between single backticks with no backtick inside, so ``` ``a`b`` ``` rendered as the span `a` followed by loose text. A run of N backticks now opens a span that closes on a run of N, and one space is stripped from each end when both are present, as CommonMark specifies. Pairing the runs is done by scanning rather than by a backreferencing regex: `` (`+)([^\n]*?)\1 `` re-scans the rest of the line for every opener that never closes, which is superlinear on a reply whose backtick runs are all of different lengths — 2.5 seconds on a 256KB reply, on the event loop, against under a millisecond for the scan. This is what lets the blocked-tool-call line print an argument containing backticks: `` Bash(`echo `whoami``) `` names the command that was actually refused, where dropping the backticks would have named a different one
Expand Down
22 changes: 20 additions & 2 deletions src/claude/sdk_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,18 @@ def _to_int(value: Any) -> Optional[int]:
# control request -- leaving the checks below inert. See issue #219.
GUARDED_TOOLS = FILE_TOOLS | BASH_TOOLS


def _allow_rule_base_name(rule: str) -> str:
"""Return the tool an allow rule names, without its scope.

Allow rules may use the CLI's scoped syntax -- ``Bash(git:*)``,
``Read(//etc/**)`` -- where the tool name is the part before ``(`` and
the scope only narrows which calls the rule matches. Gating decisions
are per tool, so they compare this base name. See issue #244.
"""
return rule.split("(", 1)[0].strip()


# Keys under which the guarded file tools pass their target path.
_FILE_PATH_KEYS = ("file_path", "path", "notebook_path")

Expand Down Expand Up @@ -489,10 +501,16 @@ def _stderr_callback(line: str) -> None:
tools_to_strip = tools_to_strip | GUARDED_TOOLS

if tools_to_strip:
gated = [t for t in sdk_allowed_tools if t in tools_to_strip]
gated = [
t
for t in sdk_allowed_tools
if _allow_rule_base_name(t) in tools_to_strip
]
if gated:
sdk_allowed_tools = [
tool for tool in sdk_allowed_tools if tool not in tools_to_strip
tool
for tool in sdk_allowed_tools
if _allow_rule_base_name(tool) not in tools_to_strip
]
logger.debug(
"Routing guarded tools through can_use_tool",
Expand Down
158 changes: 158 additions & 0 deletions tests/unit/test_claude/test_scoped_allow_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
"""Regression tests for #244: scoped allow rules for guarded tools.

``ClaudeSDKManager.execute_command`` strips guarded tools (and tools gated
behind interactive approval) from ``allowed_tools`` so the CLI routes those
calls through ``can_use_tool`` instead of pre-approving them (#219). The
strip used to compare entries by exact name, so a scoped rule such as
``Bash(git:*)`` never matched ``Bash`` and was passed through to the CLI,
which pre-approved every call it matched. These tests pin that allow rules
are matched by the tool they name -- the part before ``(``.
"""

from unittest.mock import AsyncMock, MagicMock, patch

import pytest
from claude_agent_sdk import AssistantMessage, ResultMessage, TextBlock

from src.claude.sdk_integration import ClaudeSDKManager
from src.config.settings import Settings


@pytest.fixture(autouse=True)
def _patch_parse_message():
"""Patch parse_message as identity so mocks can yield typed Message objects."""
with patch("src.claude.sdk_integration.parse_message", side_effect=lambda x: x):
yield


def _make_assistant_message(text="Test response"):
"""Create an AssistantMessage with proper structure for current SDK version."""
return AssistantMessage(
content=[TextBlock(text=text)],
model="claude-sonnet-4-20250514",
)


def _make_result_message(**kwargs):
"""Create a ResultMessage with sensible defaults."""
defaults = {
"subtype": "success",
"duration_ms": 1000,
"duration_api_ms": 800,
"is_error": False,
"num_turns": 1,
"session_id": "test-session",
"total_cost_usd": 0.05,
"result": "Success",
}
defaults.update(kwargs)
return ResultMessage(**defaults)


def _mock_client(*messages):
"""Create a mock ClaudeSDKClient that yields the given messages."""
client = AsyncMock()
client.connect = AsyncMock()
client.disconnect = AsyncMock()
client.query = AsyncMock()

async def receive_raw_messages():
for msg in messages:
yield msg

query_mock = AsyncMock()
query_mock.receive_messages = receive_raw_messages
client._query = query_mock

return client


def _mock_client_factory(*messages, capture_options=None):
"""Create a factory that returns a mock client, optionally capturing options."""

def factory(options):
if capture_options is not None:
capture_options.append(options)
return _mock_client(*messages)

return factory


async def _capture_options(manager, tmp_path):
"""Run execute_command against a mock client and return the options used."""
captured_options = []
mock_factory = _mock_client_factory(
_make_assistant_message("ok"),
_make_result_message(total_cost_usd=0.01),
capture_options=captured_options,
)
with patch("src.claude.sdk_integration.ClaudeSDKClient", side_effect=mock_factory):
await manager.execute_command(prompt="Test", working_directory=tmp_path)
assert len(captured_options) == 1
return captured_options[0]


def _config(tmp_path, **overrides):
return Settings(
telegram_bot_token="test:token",
telegram_bot_username="testbot",
approved_directory=tmp_path,
claude_timeout_seconds=2,
**overrides,
)


def _validator(tmp_path):
validator = MagicMock()
validator.validate_path = MagicMock(return_value=(True, tmp_path, None))
return validator


class TestScopedAllowRules:
"""Scoped allow rules must not pre-approve guarded or gated tools."""

async def test_scoped_rules_for_guarded_tools_are_stripped(self, tmp_path):
"""Bash(git:*), Read(//etc/**) and Write(*) name guarded tools."""
manager = ClaudeSDKManager(
_config(
tmp_path,
claude_allowed_tools=[
"Bash(git:*)",
"Read(//etc/**)",
"Write(*)",
"Grep",
],
),
security_validator=_validator(tmp_path),
)
options = await _capture_options(manager, tmp_path)

assert options.allowed_tools == ["Grep"]

async def test_scoped_rule_for_unguarded_tool_is_kept(self, tmp_path):
"""A scoped rule for a tool the callback does not guard stays."""
manager = ClaudeSDKManager(
_config(
tmp_path,
claude_allowed_tools=["WebFetch(domain:example.com)", "Grep"],
),
security_validator=_validator(tmp_path),
)
options = await _capture_options(manager, tmp_path)

assert "WebFetch(domain:example.com)" in options.allowed_tools
assert "Grep" in options.allowed_tools

async def test_scoped_rules_for_approval_gated_tools_are_stripped(self, tmp_path):
"""The interactive approval strip matches by base tool name too."""
manager = ClaudeSDKManager(
_config(
tmp_path,
interactive_tool_approval=True,
interactive_tool_approval_tools=["Bash", "Write"],
claude_allowed_tools=["Bash(git:*)", "Write(*)", "Read"],
)
)
options = await _capture_options(manager, tmp_path)

assert options.allowed_tools == ["Read"]
Loading