- 方案第 4 章 P0-P8 拆为 9 份独立阶段计划书,原文件只保留索引与横切章节 - 《项目完善报告》《评审与收编清单》内容拆入各阶段计划书后删除 - 统一缺陷台账 F-01…F-76(历史 71 条 + 方案补充 5 条),保留历史编号对照 - 新增 README 作为路线图索引:阶段清单、执行顺序、第 0 天清扫、台账、迭代约定
366 lines
16 KiB
Markdown
366 lines
16 KiB
Markdown
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||
> **阶段**:P6 · 工具治理:可见范围、人工确认、沙箱与密钥 | **预估**:10–12 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.7 节
|
||
> **本阶段收编缺陷**:F-37、F-38(共 2 条,明细见文末附录)
|
||
> 上一阶段:[`P5`](P5-工作流编排.md) | 下一阶段:[`P7`](P7-可观测与评测.md)
|
||
|
||
|
||
# 4.7 P6 · 工具治理:可见范围、人工确认、沙箱与密钥
|
||
|
||
## 目标
|
||
|
||
把"所有注册的工具对所有 Agent 全开放、密钥明文躺在 YAML 里、stdio 工具直接跑在宿主机"的现状,升级为**统一治理面**:谁能看见哪些工具、调用要不要人批、在什么环境里执行、密钥从哪来。对应面试官 B 的第三阶段(MCP / Worker / 执行环境安全 / Vault / 持久化记忆 / Session 生命周期)。
|
||
|
||
本阶段同时兑现 P1 留下的决策:Skill 从"仅注入 instruction"升级为"沙箱内可调用"(见 `P1-工具网关.md` 的 4.2.8 节),并移除 `skills.mode` 开关。
|
||
|
||
## 当前问题
|
||
|
||
| 问题 | 证据 |
|
||
|---|---|
|
||
| 无工具可见范围:`ChatModelNode` 把 `tool-mcp-list` 里的工具全部注册给模型 | `armory/chat_model_node.go` |
|
||
| 无权限/审批:任何工具只要注册即可被调用 | `(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go`、`ToolRouter` in `internal/domain/agent/ports/ports.go` |
|
||
| 无沙箱:`stdio` MCP 通过 `exec.Command` 直接在宿主进程组里跑 | `ai/tools.go` |
|
||
| 无密钥托管:API Key 来自 YAML + `.env` | `configs/agent/*.yaml`、`.env.example` 含疑似真实密钥 |
|
||
| 无审计:谁在什么时候调了什么工具,无记录 | 全局 |
|
||
|
||
## 设计
|
||
|
||
### 4.7.1 三层治理模型
|
||
|
||
```
|
||
① 可见范围(Visibility):模型能不能"看到"这个工具
|
||
↓
|
||
② 调用策略(Policy):看到之后,这次调用 allow / deny / require_approval
|
||
↓
|
||
③ 执行隔离(Sandbox):批准之后,在哪个环境里、以什么权限执行
|
||
```
|
||
|
||
三层职责分离的好处:可见范围是**静态配置**(启动时定),策略是**运行时判定**(按主体/参数/上下文),沙箱是**执行细节**(与策略解耦)。面试里能讲清这个分层,比笼统说"做了权限控制"高一个档次。
|
||
|
||
### 4.7.2 策略模型与求值
|
||
|
||
```go
|
||
// internal/domain/security/policy.go
|
||
type Effect string
|
||
|
||
const (
|
||
EffectAllow Effect = "allow"
|
||
EffectDeny Effect = "deny"
|
||
EffectRequireApproval Effect = "require_approval"
|
||
)
|
||
|
||
type Subject struct {
|
||
TenantID string
|
||
UserID string
|
||
Roles []string
|
||
AgentID string
|
||
}
|
||
|
||
type Request struct {
|
||
Subject Subject
|
||
Tool string
|
||
Effect tool.SideEffect
|
||
Args json.RawMessage
|
||
RunID string
|
||
SessionID string
|
||
Context map[string]any // 时间、渠道、风险分等
|
||
}
|
||
|
||
type Decision struct {
|
||
Effect Effect
|
||
RuleID string
|
||
Reason string
|
||
Approvers []string
|
||
TTL time.Duration
|
||
}
|
||
|
||
type Engine interface {
|
||
Evaluate(ctx context.Context, req Request) (Decision, error)
|
||
}
|
||
```
|
||
|
||
**求值顺序(必须确定)**:
|
||
|
||
```
|
||
1. 显式 deny 规则(任一命中 → deny,短路)
|
||
2. 显式 require_approval 规则(任一命中 → 需审批)
|
||
3. 显式 allow 规则(任一命中 → allow)
|
||
4. 默认策略:EffectRead → allow;Write/Destructive/External → require_approval(可配 deny)
|
||
```
|
||
|
||
**"deny 优先"是安全默认**:规则有冲突时永远取最严格的。规则本身用 YAML 声明 + expr 条件:
|
||
|
||
```yaml
|
||
# configs/policies.yaml
|
||
version: 1
|
||
defaults:
|
||
read: allow
|
||
write: require_approval
|
||
destructive: deny
|
||
external: require_approval
|
||
|
||
rules:
|
||
- id: deny-pii-export
|
||
match:
|
||
tool: ["crm.export*", "user.dump*"]
|
||
effect: deny
|
||
reason: "禁止导出用户明细"
|
||
|
||
- id: auto-allow-internal-search
|
||
match:
|
||
tool: ["search.*", "kb.search"]
|
||
effect: [read]
|
||
effect: allow
|
||
|
||
- id: big-refund-needs-manager
|
||
match:
|
||
tool: ["payment.refund"]
|
||
when: "args.amount > 1000"
|
||
effect: require_approval
|
||
approvers: [manager]
|
||
ttl: 30m
|
||
|
||
- id: deny-off-hours-writes
|
||
match:
|
||
effect: [write, destructive]
|
||
when: "now().Hour() < 9 || now().Hour() > 19"
|
||
effect: deny
|
||
reason: "非工作时段禁止写操作"
|
||
```
|
||
|
||
`match.tool` 支持通配,`when` 是 expr(环境变量 `args` / `subject` / `now` / `context`)。规则编译期校验、求值 p99 < 1ms,结果可按 `(tool, effect, 参数哈希)` 缓存。
|
||
|
||
### 4.7.3 人工确认(HITL)流程
|
||
|
||
```
|
||
工具调用 → Policy 判定 require_approval
|
||
│
|
||
├─ 写 agent_approval(status=pending, expires_at=now+ttl)
|
||
├─ Run 状态 → waiting_approval
|
||
├─ 发事件 approval.required(含工具名、参数摘要、风险说明)
|
||
└─ 挂起(保存检查点,释放 goroutine)
|
||
│
|
||
├─ 用户批准 → 写 decision=approved → 唤醒 Run(从检查点续跑)→ 执行工具
|
||
├─ 用户拒绝 → decision=rejected → 工具返回 "denied by user" → 模型改计划(L5 降级)
|
||
└─ 超时 → decision=expired → 同拒绝,且记录指标
|
||
```
|
||
|
||
```sql
|
||
CREATE TABLE `agent_approval` (
|
||
`id` CHAR(26) NOT NULL,
|
||
`run_id` CHAR(26) NOT NULL,
|
||
`step_id` CHAR(26) NOT NULL DEFAULT '',
|
||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||
`user_id` VARCHAR(64) NOT NULL,
|
||
`session_id` CHAR(26) NOT NULL DEFAULT '',
|
||
`tool_name` VARCHAR(128) NOT NULL,
|
||
`args_digest` CHAR(64) NOT NULL COMMENT '参数 sha256,避免存敏感原文',
|
||
`args_preview` TEXT NULL COMMENT '脱敏后的参数预览',
|
||
`risk` VARCHAR(16) NOT NULL DEFAULT 'medium',
|
||
`status` VARCHAR(16) NOT NULL DEFAULT 'pending' COMMENT 'pending|approved|rejected|expired',
|
||
`decided_by` VARCHAR(64) NOT NULL DEFAULT '',
|
||
`decided_at` DATETIME(3) NULL,
|
||
`reason` VARCHAR(512) NOT NULL DEFAULT '',
|
||
`expires_at` DATETIME(3) NOT NULL,
|
||
`created_at` DATETIME(3) NOT NULL,
|
||
PRIMARY KEY (`id`),
|
||
KEY `idx_pending` (`tenant_id`,`status`,`expires_at`),
|
||
KEY `idx_run` (`run_id`)
|
||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||
```
|
||
|
||
API:
|
||
|
||
| 方法 | 路径 | 说明 |
|
||
|---|---|---|
|
||
| GET | `/api/v1/approvals?status=pending` | 待办列表 |
|
||
| POST | `/api/v1/approvals/{id}/approve` | `{reason, remember_for: session\|never}` |
|
||
| POST | `/api/v1/approvals/{id}/reject` | `{reason}` |
|
||
|
||
**`remember_for: session`** 是体验关键:同一个会话内同类工具不再重复弹窗(存 `session` 级豁免表),否则用户会被审批疲劳拖死。
|
||
|
||
**挂起不能占资源**:Run 挂起时**不持有 goroutine**,靠检查点 + 事件驱动恢复。这是"waiting_approval 状态"存在的意义——如果用 `time.Sleep` 轮询,1000 个待审批请求就是 1000 个阻塞的 goroutine。
|
||
|
||
### 4.7.4 沙箱执行
|
||
|
||
```go
|
||
// internal/domain/sandbox/ports.go
|
||
type Spec struct {
|
||
Image string
|
||
Cmd []string
|
||
Env map[string]string // 只允许白名单注入
|
||
WorkDir string
|
||
Timeout time.Duration
|
||
MemoryMB int
|
||
CPUShares int
|
||
NetworkMode string // none | egress-proxy | host(仅 dev)
|
||
ReadOnlyFS bool
|
||
Mounts []Mount // 只读挂载输入,可写挂载输出
|
||
}
|
||
|
||
type Runner interface {
|
||
Run(ctx context.Context, spec Spec, stdin []byte) (Result, error)
|
||
Kill(ctx context.Context, id string) error
|
||
}
|
||
```
|
||
|
||
三种实现,按风险分级选择:
|
||
|
||
| 实现 | 隔离级别 | 适用 | 依赖 |
|
||
|---|---|---|---|
|
||
| `local` | 无(仅超时+资源限制) | 本地开发 | — |
|
||
| `docker` | 容器(只读根、无网、内存/CPU 限额、非 root) | stdio MCP、代码执行 | Docker |
|
||
| `wasm`(wazero) | 进程内沙箱 | 纯计算型插件 | 无 |
|
||
|
||
默认:`stdio` MCP 与"执行代码"类工具走 `docker`;`local` 仅在 `env=local` 且显式开启时可用。
|
||
|
||
**出口网络**:`egress-proxy` 模式通过一个白名单代理(只允许配置的域名)出网,防止工具被诱导外发数据(prompt injection 的常见利用链)。
|
||
|
||
### 4.7.5 密钥托管(Vault)
|
||
|
||
```go
|
||
// internal/domain/security/secret.go
|
||
type Ref struct {
|
||
Provider string // env | file | kms
|
||
Path string // e.g. "agent/testAgent03/api-key"
|
||
Key string
|
||
}
|
||
|
||
type Resolver interface {
|
||
Resolve(ctx context.Context, ref Ref) (string, error)
|
||
}
|
||
```
|
||
|
||
配置里不再写明文:
|
||
|
||
```yaml
|
||
ai-api:
|
||
base-url: ${BAIDU_BASE_URL}
|
||
api-key: ${vault:agents/testAgent03#api_key}
|
||
```
|
||
|
||
四条规则:
|
||
|
||
1. **懒解析**:只在真正调用时解析,不启动时全量解密(减少密钥驻留时间)。
|
||
2. **绝不落日志**:日志/事件/trace 统一过 `Redact` 中间件,按正则与已知密钥值做掩码(`sk-****abcd`)。
|
||
3. **可轮换**:`file` provider 监听文件变更热重载;KMS 按 TTL 缓存。
|
||
4. **最小暴露**:只有需要工具的 Executor 能拿到解引用能力,模型永远看不到密钥。
|
||
|
||
### 4.7.6 MCP 生命周期治理
|
||
|
||
| 能力 | 说明 |
|
||
|---|---|
|
||
| Server 注册表 | 每个 MCP Server 一条记录:名称、传输、健康状态、工具清单、最后发现时间 |
|
||
| 健康检查 | 每 30s `tools/list` 探活;连续 3 次失败标记 `unhealthy`,其工具从模型可见列表移除 |
|
||
| 工具热刷新 | 定时(5min)或手动 `POST /admin/mcp/{name}/refresh` 重新发现 |
|
||
| 熔断开关 | `POST /admin/mcp/{name}/disable` 立即摘除该 Server 的所有工具 |
|
||
| 命名空间 | 工具名统一 `server.tool`,避免不同 Server 同名覆盖(修复 F-13) |
|
||
| 速率限制 | 每 Server 独立令牌桶,防止一个 Server 拖垮全局 |
|
||
|
||
## 涉及的代码模块
|
||
|
||
| 类型 | 文件 | 改动要点 |
|
||
|---|---|---|
|
||
| 新增 | `internal/domain/security/policy.go` | Subject/Request/Decision/Engine |
|
||
| 新增 | `internal/domain/security/approval.go` | Approval 聚合、状态机、TTL |
|
||
| 新增 | `internal/domain/security/secret.go` | Ref/Resolver 端口 |
|
||
| 新增 | `internal/domain/security/redact.go` | 脱敏规则 |
|
||
| 新增 | `internal/domain/sandbox/ports.go` | Spec/Runner |
|
||
| 新增 | `internal/domain/skill/exec.go` | Skill Runner(脚本执行契约,见 `P1-工具网关.md` 的 4.2.8 节) |
|
||
| 新增 | `internal/infrastructure/skill/executor.go` | 把 Skill script 包装为 `tool.Spec`,执行体走 `sandbox.Runner` |
|
||
| 新增 | `internal/infrastructure/security/policy_yaml.go` | 规则加载、expr 求值、缓存 |
|
||
| 新增 | `internal/infrastructure/security/approval_repo.go` | approval 表读写 |
|
||
| 新增 | `internal/infrastructure/security/vault_env.go` / `vault_file.go` | 两种 Resolver |
|
||
| 新增 | `internal/infrastructure/sandbox/local.go` / `docker.go` / `wasm.go` | 三种 Runner |
|
||
| 新增 | `internal/infrastructure/sandbox/egress.go` | 出口白名单代理 |
|
||
| 新增 | `internal/domain/tool/approval_gate.go` | 网关第 5 步的实现 |
|
||
| 新增 | `migrations/0004_security.up.sql` | agent_approval / agent_audit |
|
||
| 修改 | `internal/domain/tool/gateway.go` | 接入 Policy 与 Approval |
|
||
| 修改 | `internal/domain/agent/service/armory/chat_model_node.go` | 只注册 `Visibility=model` 的工具 |
|
||
| 修改 | `internal/infrastructure/ai/tools.go` | stdio 执行改走 sandbox.Runner |
|
||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Policy/Vault/Sandbox |
|
||
| 修改 | `internal/trigger/http/*` | approvals/admin 端点 + 鉴权中间件 |
|
||
| 修改 | `configs/agent/*.yaml` | 密钥改 `${vault:...}`;工具加 `visibility` |
|
||
|
||
## 验收标准
|
||
|
||
1. **可见范围**:给 Agent 配 `visibility: human_only` 的工具,模型请求中**不出现**该工具(抓包断言),但人工可以直接调用。
|
||
2. **策略生效**:`deny` 规则命中时工具不执行(下游 mock 零调用),返回 `permission` 错误且 Run 继续(模型改计划)。
|
||
3. **审批闭环**:写类工具触发 `waiting_approval`,批准后 3s 内继续执行;拒绝则模型收到 denied 并改口;超时自动拒绝。
|
||
4. **挂起不占资源**:10 个并发待审批 Run,进程 goroutine 数不增长(对比基线 < +5)。
|
||
5. **沙箱隔离**:stdio 工具尝试 `curl` 外网被拒;尝试写 `/etc` 失败;内存超 256MB 被杀;超时被杀。
|
||
6. **密钥不泄露**:全量日志 grep 不到任何真实 key;`args_preview` 中敏感字段已掩码。
|
||
7. **MCP 摘除**:disable 某 Server 后 1s 内其工具从模型可见列表消失,调用返回 `not_found` 而非挂起。
|
||
|
||
## 测试策略
|
||
|
||
- 策略引擎:50 条规则冲突矩阵表驱动测试,断言"deny 优先"。
|
||
- 审批:状态机单测 + 集成(真 DB + HTTP)。
|
||
- 沙箱:用 alpine 镜像跑 `sh -c` 测试网络/写盘/资源三类限制;CI 标记 `-tags=sandbox`,无 Docker 时跳过。
|
||
- 安全:`gosec` + 自写测试断言日志脱敏(构造假密钥写入日志,断言输出为掩码)。
|
||
|
||
## 风险与回滚
|
||
|
||
| 风险 | 缓解 |
|
||
|---|---|
|
||
| 审批导致体验断崖 | `remember_for: session`;只对 write/destructive 默认审批;read 全自动 |
|
||
| 沙箱性能开销(容器启动 ~300ms) | 预热容器池;纯计算走 wasm;非高风险工具走 local+超时 |
|
||
| 策略规则写错导致全拒 | 启动时 dry-run 校验 + `policy.mode=shadow`(只记录不拦截)灰度 |
|
||
| Vault 不可用导致全站不可用 | 本地缓存 + 启动时预热 + 降级为 env(告警) |
|
||
|
||
---
|
||
|
||
---
|
||
|
||
## 附录:本阶段收编的缺陷(2 条)
|
||
|
||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||
|
||
### F-37 `stdio` / `local` 传输运行时不可执行
|
||
|
||
**位置**:`validateMCPConfig` in `internal/infrastructure/ai/tools.go`(构建)、`CallTool` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||
|
||
**问题概述**:配置层支持 stdio/local,`buildStdioMCPTools` 会构建 `MCPTool`,但运行时 `CallTool` 只处理 `clients` 里的 SSE 客户端,stdio/local 一律报「transport not supported in runtime」/「not callable」。此外 local 传输是更彻底的桩:`buildLocalMCPTools`(`validateMCPConfig` in `internal/infrastructure/ai/tools.go`)只认识硬编码的 `echoLocalTool`,其他名字直接报 `local mcp tool %q is not registered in go`,而即便是 `echoLocalTool` 也没注册到 `clients`,调用时同样落到「transport not supported」。
|
||
|
||
**影响**:`stdio` 与 `local` 是「能配置不能跑」的假功能;文档(CLAUDE.md/README)却宣称支持三种传输,存在误导。
|
||
|
||
**修复方案**:
|
||
|
||
- 要么实现 stdio(启动子进程 + JSON-RPC over stdin/stdout)与 local(内置 Go 工具注册表)执行器;
|
||
- 要么在配置校验阶段直接拒绝 stdio/local,并同步修正文档,避免用户踩坑。
|
||
|
||
---
|
||
|
||
> **归属**:P6 | **状态**:✅ | **历史编号**:P1-10
|
||
>
|
||
> stdio MCP 走 docker 沙箱;local 内置工具注册表在 P6 一并补齐
|
||
|
||
### F-38 MCP 客户端连接状态没有「代际」隔离,旧连接的错误会污染新连接
|
||
|
||
**位置**:`internal/infrastructure/ai/mcp_sse_client.go`(`pending` / `streamErr` 为共享字段,`signalStreamErr` 广播)
|
||
|
||
```go
|
||
func (c *MCPSSEClient) signalStreamErr(err error) {
|
||
c.mu.Lock()
|
||
defer c.mu.Unlock()
|
||
select {
|
||
case c.streamErr <- err:
|
||
default:
|
||
}
|
||
for id, ch := range c.pending { // <- 可能已经是「新一代」的 pending
|
||
ch <- mustJSON(...)
|
||
close(ch)
|
||
delete(c.pending, id)
|
||
}
|
||
}
|
||
```
|
||
|
||
**问题概述**:`pending`、`streamErr`、`postURL` 都是客户端上的可变字段,没有按连接代际隔离。场景:连接 A 断开并触发重连(`shutdown` + 新 `ensureStarted` 生成新 `pending`/`streamErr`),但旧 `readLoop(A)` 退出前仍会执行 `signalStreamErr`,此时它遍历/写入的已经是新一代的 `pending`/`streamErr`,从而把「A 已断开」的错误广播给正在等 B 的请求。
|
||
|
||
**影响**:偶发的「刚连上却收到 stream closed / 请求失败」,难以复现和排查;并发重连时概率上升。
|
||
|
||
**修复方案**:为每次启动引入 `generation uint64`,把 `pending`/`streamErr`/`cancelFn` 收进 `connState` 结构体,`readLoop` 闭包捕获自己那一代,`signalStreamErr` 只操作自己那一代;或用 `context` 取消 + 带代际的 channel。
|
||
|
||
> **归属**:P6 | **状态**:🟡 | **历史编号**:P2-21
|
||
>
|
||
> P6 的 `connState` 代际隔离重构会覆盖,需点名
|