#!/usr/bin/env python3 """ s03_permission.py - 权限系统 在工具执行前插入三道关卡: 关卡 1:硬性拒绝列表(rm -rf /、sudo 等) 关卡 2:规则匹配(是否写到工作区外?是否是破坏性命令?) 关卡 3:用户审批(暂停并等待确认) +-------+ +--------+ +--------+ +--------+ +------+ | Tool | -> | Gate 1 | -> | Gate 2 | -> | Gate 3 | -> | Exec | | call | | deny? | | match? | | allow? | | | +-------+ +--------+ +--------+ +--------+ +------+ | | | | v v v v (正常) (拦截) (询问用户) (用户拒绝?) Agent 循环里只新增一行: if not check_permission(block): continue 基于 s02(多工具)构建。用法: python s03_permission/code.py 需要: pip install anthropic python-dotenv + .env 中配置 ANTHROPIC_API_KEY """ import os, subprocess from pathlib import Path try: import readline readline.parse_and_bind('set bind-tty-special-chars off') readline.parse_and_bind('set input-meta on') readline.parse_and_bind('set output-meta on') readline.parse_and_bind('set convert-meta off') except ImportError: pass from anthropic import Anthropic from dotenv import load_dotenv load_dotenv(override=True) if os.getenv("ANTHROPIC_BASE_URL"): os.environ.pop("ANTHROPIC_AUTH_TOKEN", None) WORKDIR = Path.cwd() client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL")) MODEL = os.environ["MODEL_ID"] SYSTEM = f"你是位于 {WORKDIR}. 所有破坏性操作都需要用户审批。" # ═══════════════════════════════════════════════════════════ # 来自 s02 : 工具实现 # ═══════════════════════════════════════════════════════════ def run_bash(command: str) -> str: try: r = subprocess.run(command, shell=True, cwd=WORKDIR, capture_output=True, text=True, timeout=120) out = (r.stdout + r.stderr).strip() return out[:50000] if out else "(无输出)" except subprocess.TimeoutExpired: return "错误:执行超时(120 秒)" def run_read(path: str, limit: int | None = None) -> str: try: lines = (WORKDIR / path).resolve().read_text().splitlines() if limit and limit < len(lines): lines = lines[:limit] + [f"... ({len(lines) - limit} 行更多内容)"] return "\n".join(lines) except Exception as e: return f"错误:{e}" def run_write(path: str, content: str) -> str: try: file_path = (WORKDIR / path).resolve() file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(content) return f"已写入 {len(content)} 字节到 {path}" except Exception as e: return f"错误:{e}" def run_edit(path: str, old_text: str, new_text: str) -> str: try: file_path = (WORKDIR / path).resolve() text = file_path.read_text() if old_text not in text: return f"错误:在文件中未找到目标文本:{path}" file_path.write_text(text.replace(old_text, new_text, 1)) return f"已编辑 {path}" except Exception as e: return f"错误:{e}" def run_glob(pattern: str) -> str: import glob as g try: results = [] for match in g.glob(pattern, root_dir=WORKDIR): if (WORKDIR / match).resolve().is_relative_to(WORKDIR): results.append(match) return "\n".join(results) if results else "(无匹配)" except Exception as e: return f"错误:{e}" # ═══════════════════════════════════════════════════════════ # 来自 s02 (未改动): 工具定义与分发 # ═══════════════════════════════════════════════════════════ TOOLS = [ {"name": "bash", "description": "运行一条 shell 命令。", "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}, {"name": "read_file", "description": "读取文件内容。", "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "limit": {"type": "integer"}}, "required": ["path"]}}, {"name": "write_file", "description": "向文件写入内容。", "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}, {"name": "edit_file", "description": "在文件中替换一次完全匹配的文本。", "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}}, "required": ["path", "old_text", "new_text"]}}, {"name": "glob", "description": "查找匹配 glob 模式的文件。", "input_schema": {"type": "object", "properties": {"pattern": {"type": "string"}}, "required": ["pattern"]}}, ] TOOL_HANDLERS = { "bash": run_bash, "read_file": run_read, "write_file": run_write, "edit_file": run_edit, "glob": run_glob, } # ═══════════════════════════════════════════════════════════ # 新增于 s03: 三关卡权限流水线 # ═══════════════════════════════════════════════════════════ # 关卡 1:硬性拒绝列表 — 始终禁止 DENY_LIST = ["rm -rf /", "sudo", "shutdown", "reboot", "mkfs", "dd if=", "> /dev/sda"] def check_deny_list(command: str) -> str | None: for pattern in DENY_LIST: if pattern in command: return f"已拦截:'{pattern}' 位于拒绝列表中" return None # 关卡 2:规则匹配 — 根据上下文检查 PERMISSION_RULES = [ {"tools": ["read_file", "write_file", "edit_file"], "check": lambda args: not (WORKDIR / args.get("path", "")).resolve().is_relative_to(WORKDIR), "message": "写入工作区外部路径"}, {"tools": ["bash"], "check": lambda args: any(kw in args.get("command", "") for kw in ["rm ", "> /etc/", "chmod 777"]), "message": "可能具有破坏性的命令"}, ] def check_rules(tool_name: str, args: dict) -> str | None: for rule in PERMISSION_RULES: if tool_name in rule["tools"] and rule["check"](args): return rule["message"] return None # 关卡 3:用户审批 — 规则命中后等待确认 def ask_user(tool_name: str, args: dict, reason: str) -> str: print(f"\n\033[33m⚠ {reason}\033[0m") print(f" 工具:{tool_name}({args})") choice = input(" 是否允许?[y/N] ").strip().lower() return "allow" if choice in ("y", "yes") else "deny" # 流水线:三道关卡串联 def check_permission(block) -> bool: if block.name == "bash": reason = check_deny_list(block.input.get("command", "")) if reason: print(f"\n\033[31m⛔ {reason}\033[0m") return False reason = check_rules(block.name, block.input) if reason: decision = ask_user(block.name, block.input, reason) if decision == "deny": return False return True # ═══════════════════════════════════════════════════════════ # agent_loop — 与以下相同: s02, 插入 check_permission() # ═══════════════════════════════════════════════════════════ def agent_loop(messages: list): while True: response = client.messages.create( model=MODEL, system=SYSTEM, messages=messages, tools=TOOLS, max_tokens=8000, ) messages.append({"role": "assistant", "content": response.content}) if response.stop_reason != "tool_use": return results = [] for block in response.content: if block.type != "tool_use": continue print(f"\033[36m> {block.name}\033[0m") # s03 变化:执行前先经过权限流水线 if not check_permission(block): results.append({"type": "tool_result", "tool_use_id": block.id, "content": "权限被拒绝."}) continue handler = TOOL_HANDLERS.get(block.name) output = handler(**block.input) if handler else f"未知工具:{block.name}" print(str(output)[:200]) results.append({"type": "tool_result", "tool_use_id": block.id, "content": output}) messages.append({"role": "user", "content": results}) if __name__ == "__main__": print("s03: 权限系统") print("输入问题,回车发送。输入 q 退出。\n") history = [] while True: try: query = input("\033[36ms03 >> \033[0m") except (EOFError, KeyboardInterrupt): break if query.strip().lower() in ("q", "exit", ""): break history.append({"role": "user", "content": query}) agent_loop(history) for block in history[-1]["content"]: if getattr(block, "type", None) == "text": print(block.text) print()