refactor(security): 删除三份包级单例,共享数据统一挂 kstate

## 用户裁定

> 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 ——
  半成品状态长期红的判据会被人习惯性忽略,那时它就等于不存在。
This commit is contained in:
JianFeeeee
2026-11-04 11:57:48 +08:00
parent cc0eb51286
commit 47afd67ca1
44 changed files with 819 additions and 322 deletions

View File

@ -81,15 +81,15 @@ func TestE2E_RealTemplateSecretsRoundTrip(t *testing.T) {
dir := t.TempDir()
setTestCodec(t)
// 装配**进程级单例**(内核对所有插件共享的那一份)
if _, err := internalSecurity.InitGlobal(internalSecurity.Options{
// 变量库(2026-11-04:不再有进程级单例,改为显式持有并注入)
store, err := internalSecurity.MustStore(internalSecurity.Options{
Path: filepath.Join(dir, "variables.json"),
KeyFn: func() ([]byte, error) { return []byte("0123456789abcdef0123456789abcdef"), nil },
Enabled: true,
}); err != nil {
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { internalSecurity.SetGlobal(nil) })
_ = internalConfig.NewConfigRegistry
host, err := NewHost()
@ -99,7 +99,7 @@ func TestE2E_RealTemplateSecretsRoundTrip(t *testing.T) {
defer host.Close()
core := newFakeCore()
core.secretsAPI = internalSDK.NewSecretsAPI()
core.secretsAPI = internalSDK.NewSecretsAPI(store)
p := New("e2e", bin, dir, nil, host, nil)
if err := p.Start(core); err != nil {
t.Fatalf("Start: %v", err)
@ -126,9 +126,9 @@ func TestE2E_RealTemplateSecretsRoundTrip(t *testing.T) {
if !strings.Contains(got, "e2e-secret-value-9876543210") {
t.Fatalf("Fill 未换回明文: %q", got)
}
// 单例里应真的登记了
if internalSecurity.Global().Count() != 1 {
t.Fatalf("单例应有 1 条,实际 %d", internalSecurity.Global().Count())
// 变量库里应真的登记了
if store.Count() != 1 {
t.Fatalf("变量库应有 1 条,实际 %d", store.Count())
}
t.Logf("✅ 插件经内核变量库完成往返: %s", got)
}
@ -141,7 +141,7 @@ func TestE2E_PluginAndKernelShareOneVault(t *testing.T) {
dir := t.TempDir()
setTestCodec(t)
st, err := internalSecurity.InitGlobal(internalSecurity.Options{
st, err := internalSecurity.MustStore(internalSecurity.Options{
Path: filepath.Join(dir, "variables.json"),
KeyFn: func() ([]byte, error) { return []byte("0123456789abcdef0123456789abcdef"), nil },
Enabled: true,
@ -149,12 +149,11 @@ func TestE2E_PluginAndKernelShareOneVault(t *testing.T) {
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { internalSecurity.SetGlobal(nil) })
host, _ := NewHost()
defer host.Close()
core := newFakeCore()
core.secretsAPI = internalSDK.NewSecretsAPI()
core.secretsAPI = internalSDK.NewSecretsAPI(st)
p := New("e2e", bin, dir, nil, host, nil)
if err := p.Start(core); err != nil {
t.Fatal(err)
@ -189,13 +188,12 @@ func TestE2E_SecretsUnavailableWhenDisabled(t *testing.T) {
bin := buildPluginWithRealTemplate(t, secretsE2EPlugin)
dir := t.TempDir()
internalSecurity.SetGlobal(nil)
t.Cleanup(func() { internalSecurity.SetGlobal(nil) })
host, _ := NewHost()
defer host.Close()
core := newFakeCore()
core.secretsAPI = internalSDK.NewSecretsAPI()
// 未启用安全模块 ⇒ 传 nil(Available() 必须为 false,且不得 panic)
core.secretsAPI = internalSDK.NewSecretsAPI(nil)
p := New("e2e", bin, dir, nil, host, nil)
if err := p.Start(core); err != nil {
t.Fatal(err)

View File

@ -75,11 +75,9 @@ func TestE2E_RealTemplateSecurityDeclare(t *testing.T) {
dir := t.TempDir()
setTestCodec(t)
// 装配进程级 Runtime(生产同款单例;工具判定读的就是它)
prev := internalSecurity.RuntimeGlobal()
// ★ 2026-11-04:包级单例已删。Runtime 显式构造并**注入**给插件 SDK
// (生产路径同款:kstate.State.Security → plugin.Registry.SetSecurityRuntime)。
rt := internalSecurity.NewRuntime(nil)
internalSecurity.SetRuntimeGlobal(rt)
t.Cleanup(func() { internalSecurity.SetRuntimeGlobal(prev) })
_ = internalConfig.NewConfigRegistry
host, err := NewHost()
@ -90,7 +88,7 @@ func TestE2E_RealTemplateSecurityDeclare(t *testing.T) {
core := newFakeCore()
// ★ 用内核侧真实插件名注入 —— 这就是 Owner 不可伪造的来源。
core.securityAPI = internalSDK.NewSecurityAPI("e2eproc")
core.securityAPI = internalSDK.NewSecurityAPI("e2eproc", rt)
p := New("e2e", bin, dir, nil, host, nil)
if err := p.Start(core); err != nil {
t.Fatalf("Start: %v", err)

View File

@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/JianFeeeee/HologramAgent/internal/security"
"log"
"os"
"path/filepath"
@ -79,10 +80,24 @@ type Registry struct {
// kernelCtl 是内核重启/关机通道(装配时注入,可 nil)。
// 只对声明了该能力的内置插件可见(目前是 WebUI)。
kernelCtl sdk.KernelControlAPI
mu sync.RWMutex
plugins map[string]sdk.Plugin
instances []sdk.Plugin
factories map[string]NativeFactory
// secretStore 是**变量库**(凭据别名),供 sdk.SecretsAPI 桥接。
//
// ★ 为什么是注入而不是 security.Global()(2026-11-04):
// 包级单例已被删除(它绕开了内核统一挂载点)。现在由 plugin-host
// 模块从 ks.Security 取出来注入。
//
// nil 合法:未启用安全模块时 SecretsAPI.Available() == false。
secretStore *security.Store
// securityRT 是安全运行时(sdk 的事件闸门 + 档位声明面需要)。
// 与 secretStore 同源(都来自 kstate.State.Security),分两个字段是因为
// 消费方要的东西不同:SecretsAPI 只要 Store,EventsAPI/DeclareProfile 要 Runtime。
securityRT *security.Runtime
mu sync.RWMutex
plugins map[string]sdk.Plugin
instances []sdk.Plugin
factories map[string]NativeFactory
pluginAutoRestart map[string]bool
sdkRefs map[string]*sdk.PluginSDK
@ -330,6 +345,21 @@ func (r restartOnly) RequestKernelShutdown(reason string) error {
// ★ 为何用 setter 而不是构造参数:internal/plugin 不能 import cmd/homed
//
// (那是反向依赖,且 cmd 包不可被 import)。用接口 + setter 打破方向。
//
// SetSecurityRuntime 注入安全运行时(plugin-host 模块装配时调用)。
func (r *Registry) SetSecurityRuntime(rt *security.Runtime) {
r.mu.Lock()
defer r.mu.Unlock()
r.securityRT = rt
}
// SetSecretStore 注入变量库(plugin-host 模块装配时调用)。
func (r *Registry) SetSecretStore(s *security.Store) {
r.mu.Lock()
defer r.mu.Unlock()
r.secretStore = s
}
func (r *Registry) SetKernelControl(k sdk.KernelControlAPI) {
r.mu.Lock()
defer r.mu.Unlock()
@ -556,6 +586,8 @@ type sdkDeps struct {
stageHost sdk.ToolSource
idx *memory.Indexer
kernelCtl sdk.KernelControlAPI
secretStore *security.Store
securityRT *security.Runtime
}
// snapshotDeps 在一次 RLock 内取走 buildSDK 需要的全部依赖。
@ -585,6 +617,8 @@ func (r *Registry) snapshotDeps() sdkDeps {
stageHost: r.stageHost,
idx: r.idx,
kernelCtl: r.kernelCtl,
secretStore: r.secretStore,
securityRT: r.securityRT,
}
}
@ -757,13 +791,14 @@ func (r *Registry) buildSDK(name string) *sdk.PluginSDK {
Knowledge: sdk.NewKnowledge(deps.ks),
LLM: sdk.NewLLM(deps.mgr, deps.cfgReg, deps.lua, deps.baseKey),
Settings: sett,
// ★ 变量库:桥接到进程级 security.Global()(**不另建存储**)。
// 内核未启用安全模块时它 Available()==false(不是 nil)。
Secrets: sdk.NewSecretsAPI(),
// ★ 变量库:桥接到**注入的** Store(不另建存储)。
// 内核未启用安全模块时为 nil ⇒ Available()==false(不是 nil API)。
Secrets: sdk.NewSecretsAPI(deps.secretStore),
SecurityRuntime: deps.securityRT,
// ★ 策略声明面:插件**声明**档位(qq.owner / qq.guest…),
// 判定仍在内核 security.Runtime。Owner 由内核用真实插件名填,
// 插件无法伪造身份(见 internal/sdk/security_impl.go)。
Security: sdk.NewSecurityAPI(name),
Security: sdk.NewSecurityAPI(name, deps.securityRT),
// ★ 随包资源:读 <插件目录>/rawfile/,可写目录 <插件目录>/work/。
// 内置插件(无独立目录)拿到的路径不存在,Read 会明确报错 ——
// 那是对的:它们本来就没有随包资源。