()
| 243 | # ============================================================ |
| 244 | |
| 245 | def main(): |
| 246 | print("=" * 60) |
| 247 | print("Tutorial 04: Permission System 权限系统演示") |
| 248 | print("=" * 60) |
| 249 | |
| 250 | # 创建一个 WorkspaceWrite 模式的策略 |
| 251 | # 并设置每个工具的权限要求 |
| 252 | policy = ( |
| 253 | PermissionPolicy(PermissionMode.WORKSPACE_WRITE) |
| 254 | .with_tool_requirement("read_file", PermissionMode.READ_ONLY) |
| 255 | .with_tool_requirement("write_file", PermissionMode.WORKSPACE_WRITE) |
| 256 | .with_tool_requirement("bash", PermissionMode.DANGER_FULL_ACCESS) |
| 257 | .with_tool_requirement("grep", PermissionMode.READ_ONLY) |
| 258 | ) |
| 259 | |
| 260 | # 准备不同的 Prompter |
| 261 | auto_allow = AlwaysAllowPrompter() |
| 262 | auto_deny = AlwaysDenyPrompter() |
| 263 | |
| 264 | print("\n--- 场景 1: 权限足够的工具 ---") |
| 265 | for tool in ["read_file", "write_file", "grep"]: |
| 266 | allowed, reason = policy.authorize(tool, '{"path": "test.py"}') |
| 267 | print(f" {tool}: {'ALLOW' if allowed else 'DENY'} — {reason}") |
| 268 | |
| 269 | print("\n--- 场景 2: 权限不够,没有 Prompter ---") |
| 270 | allowed, reason = policy.authorize("bash", '{"command": "rm -rf /"}') |
| 271 | print(f" bash: {'ALLOW' if allowed else 'DENY'} — {reason}") |
| 272 | |
| 273 | print("\n--- 场景 3: 权限不够,用 AlwaysAllow Prompter 自动批准 ---") |
| 274 | allowed, reason = policy.authorize("bash", '{"command": "echo hello"}', auto_allow) |
| 275 | print(f" bash: {'ALLOW' if allowed else 'DENY'} — {reason}") |
| 276 | |
| 277 | print("\n--- 场景 4: 权限不够,用 AlwaysDeny Prompter 自动拒绝 ---") |
| 278 | allowed, reason = policy.authorize("bash", '{"command": "echo hello"}', auto_deny) |
| 279 | print(f" bash: {'ALLOW' if allowed else 'DENY'} — {reason}") |
| 280 | |
| 281 | print("\n--- 场景 5: Allow 模式(全部放行)---") |
| 282 | allow_policy = PermissionPolicy(ALLOW_MODE) |
| 283 | allowed, reason = allow_policy.authorize("bash", '{"command": "rm -rf /"}') |
| 284 | print(f" bash (allow mode): {'ALLOW' if allowed else 'DENY'} — {reason}") |
| 285 | |
| 286 | print("\n--- 场景 6: ReadOnly 模式(最严格)---") |
| 287 | readonly_policy = ( |
| 288 | PermissionPolicy(PermissionMode.READ_ONLY) |
| 289 | .with_tool_requirement("read_file", PermissionMode.READ_ONLY) |
| 290 | .with_tool_requirement("bash", PermissionMode.DANGER_FULL_ACCESS) |
| 291 | ) |
| 292 | allowed, reason = readonly_policy.authorize("read_file", '{"path": "test.py"}') |
| 293 | print(f" read_file: {'ALLOW' if allowed else 'DENY'} — {reason}") |
| 294 | allowed, reason = readonly_policy.authorize("bash", '{"command": "ls"}') |
| 295 | print(f" bash: {'ALLOW' if allowed else 'DENY'} — {reason}") |
| 296 | |
| 297 | # 解说 |
| 298 | print("\n" + "=" * 60) |
| 299 | print("关键理解要点:") |
| 300 | print("=" * 60) |
| 301 | print(""" |
| 302 | 1. 权限等级(从低到高): |
no test coverage detected