s03:Permission——执行前做权限判断
s03:Permission——执行前做权限判断
“先划边界,再给自由。” ——先判断操作能不能做,要不要问用户。
问题
s02 的 Agent 有 5 个工具。file tools 受 safe_path 保护,但 bash 不受限制。让它”清理一下项目”,可能执行 rm -rf /。
安全不能靠信任模型,要靠代码——在工具执行之前做判断。
解决方案
在工具执行前插入 check_permission()——每个工具调用经过三道闸门:
| 闸门 | 作用 | 命中后 |
|---|---|---|
| 1. 拒绝列表 | 永远禁止的操作(rm -rf /、sudo) |
直接拒绝 |
| 2. 规则匹配 | 取决于上下文的操作(写工作区外、rm 文件) |
交给闸门 3 |
| 3. 用户审批 | 闸门 2 命中后,暂停等用户确认 | 用户决定 |
三道都没命中 → 直接执行。大部分日常操作走这条路。
工作原理
闸门 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"Blocked: '{pattern}' is on the deny list"
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": "Access outside workspace",
},
{
"tools": ["bash"],
"check": lambda args: any(kw in args.get("command", "")
for kw in ["rm ", "> /etc/", "chmod 777"]),
"message": "Potentially destructive command",
},
]
闸门 3:规则命中后,暂停等用户输入:
def ask_user(tool_name: str, args: dict, reason: str) -> str:
print(f"\n⚠ {reason}")
print(f" Tool: {tool_name}({args})")
choice = input(" Allow? [y/N] ").strip().lower()
return "allow" if choice in ("y", "yes") else "deny"
三道闸门串在一起,插在工具执行之前:
def check_permission(block) -> bool:
# 闸门 1: 硬拒绝
if block.name == "bash":
reason = check_deny_list(block.input.get("command", ""))
if reason:
print(f"\n⛔ {reason}")
return False
# 闸门 2 + 3: 规则匹配 → 用户审批
reason = check_rules(block.name, block.input)
if reason:
decision = ask_user(block.name, block.input, reason)
if decision == "deny":
return False
return True
循环里只加了一行:
for block in response.content:
if block.type == "tool_use":
if not check_permission(block): # ← 新增这行
results.append({... "content": "Permission denied."})
continue
output = TOOL_HANDLERS[block.name](**block.input) # s02 原有
对比上一章
| 组件 | s02 | s03 |
|---|---|---|
| 安全模型 | 无(信任模型) | 三道闸门权限管线 |
| 新函数 | — | check_deny_list, check_rules, ask_user, check_permission |
| 循环 | 直接执行所有工具 | 执行前插入 check_permission() |
试一下
python s03_permission/code.py
试试:
Create a file called test.txt in the current directory(直接通过)Delete the file test.txt(bash + rm 触发闸门 2)Try to write a file to /etc/something(写工作区外,触发闸门 2)
观察:哪些操作直接通过?哪些需要确认?哪些被直接拒绝?
接下来
权限检查做了——但每次都在循环里硬编码 check_permission()。如果还想在每次工具执行前后加日志?某些操作后自动 git commit?
s04 Hooks → 给循环加钩子,扩展逻辑挂在钩子上,循环保持干净。