|
| 1 | +# Tencent is pleased to support the open source community by making tRPC-Agent-Python available. |
| 2 | +# |
| 3 | +# Copyright (C) 2026 Tencent. All rights reserved. |
| 4 | +# |
| 5 | +# tRPC-Agent-Python is licensed under Apache-2.0. |
| 6 | +"""Tests for tool safety filter, audit, and executor wrapper.""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import json |
| 11 | +from unittest.mock import MagicMock |
| 12 | + |
| 13 | +from opentelemetry import trace |
| 14 | + |
| 15 | +from trpc_agent_sdk.code_executors import BaseCodeExecutor |
| 16 | +from trpc_agent_sdk.code_executors import CodeBlock |
| 17 | +from trpc_agent_sdk.code_executors import CodeExecutionInput |
| 18 | +from trpc_agent_sdk.code_executors import CodeExecutionResult |
| 19 | +from trpc_agent_sdk.code_executors import create_code_execution_result |
| 20 | +from trpc_agent_sdk.context import AgentContext |
| 21 | +from trpc_agent_sdk.context import InvocationContext |
| 22 | +from trpc_agent_sdk.tools import FunctionTool |
| 23 | +from trpc_agent_sdk.tools.safety import SafetyDecision |
| 24 | +from trpc_agent_sdk.tools.safety import SafetyGuardedCodeExecutor |
| 25 | +from trpc_agent_sdk.tools.safety import SafetyPolicy |
| 26 | +from trpc_agent_sdk.tools.safety import ToolSafetyFilter |
| 27 | + |
| 28 | + |
| 29 | +class DummyCodeExecutor(BaseCodeExecutor): |
| 30 | + calls: int = 0 |
| 31 | + |
| 32 | + async def execute_code( |
| 33 | + self, |
| 34 | + invocation_context: InvocationContext, |
| 35 | + code_execution_input: CodeExecutionInput, |
| 36 | + ) -> CodeExecutionResult: |
| 37 | + self.calls += 1 |
| 38 | + return create_code_execution_result(stdout="ok") |
| 39 | + |
| 40 | + |
| 41 | +def _mock_invocation_context() -> InvocationContext: |
| 42 | + ctx = MagicMock(spec=InvocationContext) |
| 43 | + ctx.agent = MagicMock() |
| 44 | + ctx.agent.parallel_tool_calls = False |
| 45 | + ctx.agent.before_tool_callback = None |
| 46 | + ctx.agent.after_tool_callback = None |
| 47 | + ctx.agent_context = AgentContext() |
| 48 | + return ctx |
| 49 | + |
| 50 | + |
| 51 | +async def test_filter_blocks_dangerous_tool_and_writes_audit(tmp_path): |
| 52 | + def run_command(command: str) -> dict: |
| 53 | + return {"ran": command} |
| 54 | + |
| 55 | + audit_path = tmp_path / "audit.jsonl" |
| 56 | + policy = SafetyPolicy(audit_log_path=str(audit_path)) |
| 57 | + tool = FunctionTool(run_command, filters=[ToolSafetyFilter(policy=policy)]) |
| 58 | + |
| 59 | + result = await tool.run_async(tool_context=_mock_invocation_context(), args={"command": "rm -rf /tmp/out"}) |
| 60 | + |
| 61 | + assert result["error"] == "TOOL_SAFETY_BLOCKED" |
| 62 | + report = result["safety_report"] |
| 63 | + assert report["decision"] == SafetyDecision.DENY.value |
| 64 | + assert "FILE_RECURSIVE_DELETE" in report["findings"][0]["rule_id"] |
| 65 | + |
| 66 | + lines = audit_path.read_text(encoding="utf-8").splitlines() |
| 67 | + assert len(lines) == 1 |
| 68 | + event = json.loads(lines[0]) |
| 69 | + assert event["tool_name"] == "run_command" |
| 70 | + assert event["blocked"] is True |
| 71 | + assert event["decision"] == SafetyDecision.DENY.value |
| 72 | + |
| 73 | + |
| 74 | +async def test_filter_allows_safe_tool(tmp_path): |
| 75 | + def run_command(command: str) -> dict: |
| 76 | + return {"ran": command} |
| 77 | + |
| 78 | + policy = SafetyPolicy(audit_log_path=str(tmp_path / "audit.jsonl")) |
| 79 | + tool = FunctionTool(run_command, filters=[ToolSafetyFilter(policy=policy)]) |
| 80 | + |
| 81 | + result = await tool.run_async(tool_context=_mock_invocation_context(), args={"command": "echo hello"}) |
| 82 | + |
| 83 | + assert result == {"ran": "echo hello"} |
| 84 | + |
| 85 | + |
| 86 | +def test_filter_writes_otel_span_attributes(monkeypatch, tmp_path): |
| 87 | + span = MagicMock() |
| 88 | + monkeypatch.setattr(trace, "get_current_span", lambda: span) |
| 89 | + filter_instance = ToolSafetyFilter(policy=SafetyPolicy(audit_log_path=str(tmp_path / "audit.jsonl"))) |
| 90 | + tool = MagicMock() |
| 91 | + tool.name = "exec" |
| 92 | + |
| 93 | + async def run_filter(): |
| 94 | + from trpc_agent_sdk.abc import FilterResult |
| 95 | + from trpc_agent_sdk.tools._context_var import reset_tool_var |
| 96 | + from trpc_agent_sdk.tools._context_var import set_tool_var |
| 97 | + |
| 98 | + token = set_tool_var(tool) |
| 99 | + try: |
| 100 | + rsp = FilterResult() |
| 101 | + await filter_instance._before(AgentContext(), {"command": "rm -rf /tmp/out"}, rsp) |
| 102 | + return rsp |
| 103 | + finally: |
| 104 | + reset_tool_var(token) |
| 105 | + |
| 106 | + import asyncio |
| 107 | + |
| 108 | + rsp = asyncio.run(run_filter()) |
| 109 | + assert rsp.is_continue is False |
| 110 | + span.set_attribute.assert_any_call("tool.safety.decision", SafetyDecision.DENY.value) |
| 111 | + span.set_attribute.assert_any_call("tool.safety.blocked", True) |
| 112 | + |
| 113 | + |
| 114 | +async def test_code_executor_wrapper_blocks_before_delegate(tmp_path): |
| 115 | + delegate = DummyCodeExecutor() |
| 116 | + executor = SafetyGuardedCodeExecutor( |
| 117 | + delegate=delegate, |
| 118 | + policy=SafetyPolicy(audit_log_path=str(tmp_path / "audit.jsonl")), |
| 119 | + ) |
| 120 | + |
| 121 | + result = await executor.execute_code( |
| 122 | + MagicMock(spec=InvocationContext), |
| 123 | + CodeExecutionInput(code_blocks=[CodeBlock(language="python", code='open(".env").read()')]), |
| 124 | + ) |
| 125 | + |
| 126 | + assert "TOOL_SAFETY_BLOCKED" in result.output |
| 127 | + assert delegate.calls == 0 |
| 128 | + |
| 129 | + |
| 130 | +async def test_code_executor_wrapper_delegates_safe_code(tmp_path): |
| 131 | + delegate = DummyCodeExecutor() |
| 132 | + executor = SafetyGuardedCodeExecutor( |
| 133 | + delegate=delegate, |
| 134 | + policy=SafetyPolicy(audit_log_path=str(tmp_path / "audit.jsonl")), |
| 135 | + ) |
| 136 | + input_data = CodeExecutionInput(code_blocks=[CodeBlock(language="python", code="print('ok')")]) |
| 137 | + |
| 138 | + result = await executor.execute_code(MagicMock(spec=InvocationContext), input_data) |
| 139 | + |
| 140 | + assert "ok" in result.output |
| 141 | + assert delegate.calls == 1 |
0 commit comments