mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-11-05 16:57:32 +00:00
## 用户裁定
> secutiry 的实现也是错误的,所有共享数据统一挂载一个 kernel 提供的
> 挂载点上暴露。
> store也应该调用security的加密能力!
## 缺陷
security 包原有**三份**独立包级单例,各自被 InitXxx/SetXxx 装入、
各自有访问器,三份都绕开了内核统一挂载点 kstate.State:
global *Store 变量库(凭据别名) Global()
runtime *Runtime 安全防火墙 RuntimeGlobal()
globalCodec *Codec 配置落盘加密 ConfigCodec()
## 为什么单例是错的(不是"多一个全局变量")
本 agent 的 a.security 与 security.Global() 是**两个独立变量**。
正常装配下它们恰好指向同一份数据,但"恰好"不是保证:
· 测试替身:测试装单例、被测代码用 agent 字段 ⇒ 测的与跑的不是同一份
· 多 Runtime:两个内核实例/热重载时单例只有一份,另一方被覆盖
· 装配顺序:单例装晚了,先注册的 provider 就没被装饰
第三条**曾真实存在**:ProviderManager.Register 在注册时读单例套装饰器,
而 llm 模块原本不声明 FacSecurity 依赖 —— 顺序正确纯属巧合。
改动过程中判据如实报红 640 次泄漏。
## 本次做的(T3.1 + T3.3)
### 删 global *Store → 注入
变量库的唯一来源是 security 模块产出的 Runtime,经注入面分发:
AgentConfig.Security → a.security.Store() → a.secretStore()
ProviderManager.SetSecretStore
plugin.Registry.SetSecretStore → sdk.NewSecretsAPI(store)
core 的 4 处 security.Global()(output/toolcall/tooldefs/secret_tools)
改为 a.secretStore();context 与 stageHost 改为注入字段;
provider 装饰器改为读注入的 Store。
### 删 runtime *Runtime → 注入
plugin.Registry.SetSecurityRuntime → sdk.NewSecurityAPI(name, rt)
→ sdk.newEventsAPI(name, bus, rt)
Prepare 的幂等缓存改为 kernelmod/security 私有变量 ——
装配器私有,不再是任何包都能取的公开访问器。
### 顺带删死代码
security.FillToolArgs / FillPayload 生产调用者为 0(StageHost 已自己
用注入的 Store 做同一件事),连同只测它们的判据一起删除。
### llm 模块补 FacSecurity 依赖
这是**真实存在**的依赖:注册 provider 时要套出向装饰器,而装饰器需要
变量库。此前靠"单例先装了"掩盖了顺序错误。
## 判据(均经变异验证)
TestNoPackageLevelSingletons 源码扫描;加回 var global ⇒ 红(实测)
TestMustStoreDoesNotRegisterGlobally 两次 MustStore 必须得到不同实例
TestStoreEncryptsWithOwnKey 落盘无明文 + 重载可解
## 验证
go build ./... PASS
go vet ./... PASS
gofmt -l 干净
go test ./... -count=1 63 包全过,0 FAIL
干净检出(git worktree) build + 3 包测试全绿
## 未做(见 kernelplan.md T3.2)
globalCodec 收敛 + Store 复用 Codec
还牵涉 config 的 6 处调用点与**存量密文惰性迁移**,单独一步做。
TestNoPackageLevelSingletons 的禁表暂不含 globalCodec ——
半成品状态长期红的判据会被人习惯性忽略,那时它就等于不存在。
176 lines
6.5 KiB
Go
176 lines
6.5 KiB
Go
package sdk
|
||
|
||
// 受限事件总线的判据。
|
||
//
|
||
// 设计前提(用户 2026-10-27):现在有 security 模块兜底,可以给插件开事件总线,
|
||
// 但只能是**受限的一条缝**——白名单类型、自己的命名空间、载荷过闸。
|
||
// 每条判据都在问:插件能不能借事件总线做超出边界的事?
|
||
|
||
import (
|
||
"strings"
|
||
"testing"
|
||
|
||
"github.com/JianFeeeee/HologramAgent/internal/events"
|
||
"github.com/JianFeeeee/HologramAgent/internal/security"
|
||
pubsdk "github.com/JianFeeeee/hologramagentsdk/sdk"
|
||
)
|
||
|
||
// newTestEvents 构造一个**已装上安全闸门**的受限事件面。
|
||
//
|
||
// ## ★ 为什么必须装 Guard(2026-10-29 收敛后)
|
||
//
|
||
// 此前 `sdk/events.go` 自己查策略(checkPublish/checkSubscribe/scrubOut),
|
||
// 所以测试里的裸 bus 也能"看起来工作"。收敛后授权与脱敏全部归
|
||
// `security.eventGuard`,而闸门是挂在总线上的 —— **测试不装 Guard,
|
||
// 就等于在测一条没有执行者的策略**,于是判据会假绿。
|
||
//
|
||
// 这正好顺便钉住了生产装配要求:**总线必须带闸门**,否则策略不生效。
|
||
func newTestEvents(t *testing.T, name string) (pubsdk.EventsAPI, *events.Bus) {
|
||
t.Helper()
|
||
bus := events.NewBus()
|
||
// ★ 2026-11-04:包级单例已删,Runtime 改为**显式构造并注入**。
|
||
// NewRuntime(nil) 给 Disabled Runtime,策略仍生效 ——
|
||
// 与生产同一条纪律:关闭凭据替换 ≠ 放开授权。
|
||
rt := security.NewRuntime(nil)
|
||
if g := security.AsEventGuard(rt); g != nil {
|
||
bus.SetGuard(g)
|
||
}
|
||
return newEventsAPI(name, bus, rt), bus
|
||
}
|
||
|
||
// ① 白名单事件可发布,且 Source 被强制设成插件名(不能冒名)。
|
||
func TestEventsPublishAllowlisted(t *testing.T) {
|
||
e, bus := newTestEvents(t, "clawhubadapter")
|
||
var got *events.Event
|
||
bus.Subscribe(events.EventSkillDetected, func(evt *events.Event) { got = evt })
|
||
|
||
if err := e.Publish("skill_detected", map[string]interface{}{"path": "/x/SKILL.md"}); err != nil {
|
||
t.Fatalf("白名单事件应允许发布: %v", err)
|
||
}
|
||
if got == nil {
|
||
t.Fatal("订阅者没收到事件")
|
||
}
|
||
if got.Source != "clawhubadapter" {
|
||
t.Fatalf("Source 必须是插件名(不能冒名),实际 %q", got.Source)
|
||
}
|
||
}
|
||
|
||
// ② 越界类型必须**报错**(静默丢弃会让插件以为发成功)。
|
||
func TestEventsPublishRejectsNonAllowlisted(t *testing.T) {
|
||
e, _ := newTestEvents(t, "evil")
|
||
for _, bad := range []string{
|
||
"raw_input", // 用户输入通道
|
||
"agent_output", // 对外输出
|
||
"update_request", // 能驱动内核升级流程
|
||
"stage", // 阶段管道内部事件
|
||
"system", // 系统事件
|
||
"plugin.other.x", // 别的插件命名空间
|
||
"plugin.evil", // 缺少后缀
|
||
"", // 空类型
|
||
} {
|
||
if err := e.Publish(bad, nil); err == nil {
|
||
t.Errorf("发布 %q 应被拒绝", bad)
|
||
}
|
||
}
|
||
}
|
||
|
||
// ③ 自己的命名空间允许(插件间协作),且带后缀。
|
||
func TestEventsPublishOwnNamespace(t *testing.T) {
|
||
e, bus := newTestEvents(t, "seq")
|
||
var seen bool
|
||
bus.Subscribe(events.EventType("plugin.seq.done"), func(*events.Event) { seen = true })
|
||
if err := e.Publish("plugin.seq.done", map[string]interface{}{"n": 1}); err != nil {
|
||
t.Fatalf("自己的命名空间应允许: %v", err)
|
||
}
|
||
if !seen {
|
||
t.Fatal("订阅者没收到自己的命名空间事件")
|
||
}
|
||
}
|
||
|
||
// ④ 订阅只开白名单事件;越界订阅报错。
|
||
//
|
||
// ★ 2026-10-28 语义变更:raw_input / agent_output 改为可订阅(与
|
||
// security.EventPolicy 同步)。理由是它们是**通道出口的必需品**:
|
||
// WebUI/CLI 的对话界面靠订阅它们渲染用户消息与 agent 回复;
|
||
// 不开就等于“装监控把界面打瘫”。订阅是只读观测,真正需要收紧的是**发布**。
|
||
func TestEventsSubscribeAllowlistedOnly(t *testing.T) {
|
||
e, bus := newTestEvents(t, "p1")
|
||
for _, ok := range []string{
|
||
"tools_ready", "security_ready", "device_ready",
|
||
"raw_input", "agent_output",
|
||
"tool_call", "stage", "reasoning", "terminal_output",
|
||
} {
|
||
if _, err := e.Subscribe(ok, func(map[string]interface{}) {}); err != nil {
|
||
t.Errorf("%q 应可订阅: %v", ok, err)
|
||
}
|
||
}
|
||
|
||
// ★ update_request 可订阅(e2e 实测:内核执行器靠它收请求,
|
||
// 不开会让升级请求静默丢失)。安全边界在**发布**侧。
|
||
if _, err := e.Subscribe("update_request", func(map[string]interface{}) {}); err != nil {
|
||
t.Errorf("update_request 应可订阅: %v", err)
|
||
}
|
||
// 完全不存在的事件名也要拒
|
||
if _, err := e.Subscribe("no_such_event", func(map[string]interface{}) {}); err == nil {
|
||
t.Error("订阅未登记事件应被拒绝")
|
||
}
|
||
// 解除订阅后不再收到
|
||
cancel, err := e.Subscribe("security_ready", func(map[string]interface{}) {})
|
||
if err != nil || cancel == nil {
|
||
t.Fatalf("应能订阅 security_ready: %v", err)
|
||
}
|
||
cancel()
|
||
if bus == nil {
|
||
t.Fatal("bus 不应为 nil")
|
||
}
|
||
}
|
||
|
||
// ⑤ 载荷出向过安全闸:明文凭据被换成 @{别名},不会原样进事件。
|
||
func TestEventsPayloadIsScrubbed(t *testing.T) {
|
||
dir := t.TempDir()
|
||
store, err := security.MustStore(security.Options{
|
||
Path: dir + "/vars.json",
|
||
KeyFn: func() ([]byte, error) { return []byte("0123456789abcdef0123456789abcdef"), nil },
|
||
Enabled: true,
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
// ★ 2026-11-04:单例已删。这个用例要验证"出向载荷被闸门脱敏",
|
||
// 所以 Runtime 必须带 store;显式构造后注入给事件面。
|
||
rt := security.NewRuntime(store)
|
||
bus0 := events.NewBus()
|
||
if g := security.AsEventGuard(rt); g != nil {
|
||
bus0.SetGuard(g)
|
||
}
|
||
e := newEventsAPI("leaky", bus0, rt)
|
||
bus := bus0
|
||
var payload map[string]interface{}
|
||
bus.Subscribe(events.EventSkillDetected, func(evt *events.Event) { payload = evt.Payload })
|
||
|
||
const secret = "ghp_abcdefghijklmnopqrstuvwxyz0123456789"
|
||
if err := e.Publish("skill_detected", map[string]interface{}{"note": "token=" + secret}); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
s, _ := payload["note"].(string)
|
||
if strings.Contains(s, secret) {
|
||
t.Fatalf("载荷里的明文凭据没有被拦下: %q", s)
|
||
}
|
||
if !strings.Contains(s, "@{sec_") {
|
||
t.Fatalf("应换成变量别名,实际 %q", s)
|
||
}
|
||
}
|
||
|
||
// ⑥ 键数上限:事件是通知,不是数据通道。
|
||
func TestEventsPayloadKeyLimit(t *testing.T) {
|
||
e, _ := newTestEvents(t, "big")
|
||
limit := security.DefaultEventPolicy().MaxPayloadKeys
|
||
p := map[string]interface{}{}
|
||
for i := 0; i < limit+1; i++ {
|
||
p[string(rune('a'+i%26))+strings.Repeat("x", i)] = i
|
||
}
|
||
if err := e.Publish("skill_detected", p); err == nil {
|
||
t.Fatal("超过键数上限应报错")
|
||
}
|
||
}
|