Skip to content

Commit f0bdac0

Browse files
committed
docs(tools): add safety guard README with usage and integration guide
1 parent 10df0d7 commit f0bdac0

1 file changed

Lines changed: 157 additions & 0 deletions

File tree

docs/tools_safety/README.md

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
# Tool Script Safety Guard
2+
3+
Pre-execution safety scanning for Python scripts and Bash commands in tRPC-Agent-Python tools.
4+
5+
## Overview
6+
7+
When tRPC-Agent tools (FunctionTool, MCPTool, BashTool, etc.) execute scripts or shell commands, the Safety Guard scans the content **before execution** for security risks and can block dangerous operations.
8+
9+
## Architecture
10+
11+
```
12+
Script Input → ToolSafetyScanner → Pattern Rules (regex) + AST Rules (Python)
13+
→ Policy Matcher → Decision (allow/deny/needs_human_review)
14+
→ Audit Log (JSONL) + OTel Span Attributes
15+
```
16+
17+
The scanner also integrates as a `BaseFilter` in the tool filter chain, so it runs automatically before every tool execution.
18+
19+
## Quick Start
20+
21+
### Filter Mode (automatic)
22+
23+
```python
24+
from trpc_agent_sdk.filter import register_filter, FilterType
25+
from trpc_agent_sdk.tools.safety import ToolSafetyScanner, ToolSafetyFilter, SafetyAuditLogger
26+
from trpc_agent_sdk.tools import FunctionTool
27+
28+
scanner = ToolSafetyScanner("path/to/tool_safety_policy.yaml")
29+
audit = SafetyAuditLogger("tool_safety_audit.jsonl")
30+
31+
# Register the filter globally
32+
filter_instance = ToolSafetyFilter(scanner=scanner, audit_logger=audit)
33+
register_filter(FilterType.TOOL, "tool_safety")(type(filter_instance))
34+
35+
# Attach to a tool
36+
tool = FunctionTool(func=my_func, filters=["tool_safety"])
37+
```
38+
39+
### Standalone Mode
40+
41+
```python
42+
from trpc_agent_sdk.tools.safety import ToolSafetyScanner
43+
44+
scanner = ToolSafetyScanner("tool_safety_policy.yaml")
45+
report = await scanner.scan("rm -rf /home/user/data", tool_name="bash_tool")
46+
47+
if report.decision == Decision.DENY:
48+
print(f"Blocked: {report.findings[0].message}")
49+
```
50+
51+
## Risk Categories
52+
53+
| Category | Detection | Example Triggers |
54+
|----------|-----------|-----------------|
55+
| Dangerous File Ops | Pattern + AST | `rm -rf /`, `os.remove()`, `~/.ssh` access |
56+
| Network Access | Pattern | `curl`, `wget`, `requests.get()`, `socket.connect()` |
57+
| System Commands | Pattern + AST | `subprocess.run()`, `os.system()`, `sudo`, shell pipes |
58+
| Dependency Install | Pattern | `pip install`, `npm install`, `apt-get install` |
59+
| Resource Abuse | Pattern | `while True:`, fork bombs, `for(;;)` |
60+
| Sensitive Info Leak | Pattern + AST | Printing API keys/tokens/passwords to logs/output |
61+
62+
## Policy Configuration
63+
64+
Edit `tool_safety_policy.yaml` to control behavior without changing code:
65+
66+
- `whitelist.domains` — trusted domains allowed in network calls
67+
- `whitelist.commands` — safe shell commands to always allow
68+
- `blocklist.paths` — file paths that trigger alerts
69+
- `rules[].enabled` — enable/disable individual rules
70+
- `rules[].decision` — override per-rule decisions
71+
- `max_script_size_bytes` — reject oversized scripts
72+
- `max_scan_time_ms` — hard timeout for scanning
73+
74+
## Audit Logging
75+
76+
Events are written as JSONL to `tool_safety_audit.jsonl`:
77+
78+
```json
79+
{"timestamp":"2026-07-10T12:00:00Z","tool_name":"bash_tool","decision":"deny","risk_level":"critical","rule_ids":["DANGEROUS_DELETE_001"],"scan_duration_ms":12.5,"sanitized":false,"intercepted":true,"script_hash":"a1b2c3..."}
80+
```
81+
82+
## OpenTelemetry
83+
84+
When an active span exists, the filter sets these attributes:
85+
- `tool.safety.decision`
86+
- `tool.safety.risk_level`
87+
- `tool.safety.rule_ids`
88+
- `tool.safety.scan_duration_ms`
89+
90+
## Relationship to Other Components
91+
92+
| Component | Relationship |
93+
|-----------|-------------|
94+
| **CodeExecutor** | Safety Guard is pre-execution scanning. CodeExecutors provide runtime sandboxing. Both layers are complementary. Safety Guard does NOT replace sandbox isolation. |
95+
| **Filter System** | ToolSafetyFilter plugs into BaseTool._run_filters() via the existing filter chain. |
96+
| **Telemetry** | Decorates existing tool execution spans; does not create new spans or metrics. |
97+
| **Callbacks** | Runs alongside callback filters in the chain. Should be registered first to block before callbacks execute. |
98+
99+
## Extending with New Rules
100+
101+
### Pattern Rule
102+
103+
```python
104+
from trpc_agent_sdk.tools.safety._rules import PatternRule
105+
from trpc_agent_sdk.tools.safety._types import RiskType, RiskLevel
106+
107+
my_rule = PatternRule(
108+
rule_id="MY_CUSTOM_001",
109+
risk_type=RiskType.SYSTEM_COMMAND,
110+
risk_level=RiskLevel.HIGH,
111+
message="Custom dangerous pattern detected",
112+
recommendation="Avoid this pattern",
113+
patterns=[r"evil_pattern\b"],
114+
)
115+
BUILTIN_PATTERN_RULES.append(my_rule)
116+
```
117+
118+
### AST Rule
119+
120+
```python
121+
import ast
122+
from trpc_agent_sdk.tools.safety._rules import AstRule
123+
from trpc_agent_sdk.tools.safety._types import RiskType, RiskLevel, RuleFinding
124+
125+
def check_my_pattern(tree: ast.AST) -> list[RuleFinding]:
126+
findings = []
127+
for node in ast.walk(tree):
128+
if isinstance(node, ast.Call) and ...:
129+
findings.append(RuleFinding(
130+
rule_id="MY_AST_001",
131+
risk_type=RiskType.DANGEROUS_FILE_OP,
132+
risk_level=RiskLevel.HIGH,
133+
evidence=f"Dangerous call at line {node.lineno}",
134+
message="Custom AST check triggered",
135+
recommendation="Remove this call",
136+
))
137+
return findings
138+
139+
my_ast_rule = AstRule(
140+
rule_id="MY_AST_001",
141+
risk_type=RiskType.DANGEROUS_FILE_OP,
142+
risk_level=RiskLevel.HIGH,
143+
message="Custom AST check",
144+
recommendation="Remove this call",
145+
check=check_my_pattern,
146+
)
147+
BUILTIN_AST_RULES.append(my_ast_rule)
148+
```
149+
150+
## Known Limitations
151+
152+
1. **Pattern bypass**: Obfuscated code (e.g., `__import__("os").system(...)`) can evade regex rules
153+
2. **Bash is pattern-only**: No Bash AST parser exists; complex Bash with variable indirection may not be caught
154+
3. **False positives**: Safety tutorials or documentation scripts mentioning dangerous keywords will be flagged
155+
4. **No data flow analysis**: Syntax check only; a script reading `API_KEY` without outputting it is still flagged
156+
5. **Not a sandbox**: This is static analysis; it cannot prevent runtime exploits, memory corruption, or novel attacks
157+
6. **Whitelist fast path is conservative**: Any non-whitelisted element triggers full scan

0 commit comments

Comments
 (0)