Files
HomeAgent/internal/plugins/webui/secret_meta_test.go
JianFeeeee 5bdd0b5107 refactor(security): Store 复用 Codec 加密能力 + 删 globalCodec 单例
## 用户裁定

> store也应该调用security的加密能力!

## 改动前的事实(实测)

两套**完全重复**的 AES-256-GCM:

    Store.seal/open     store.go:372,388    裸 base64
    Codec.Seal/Open     codec.go:113,139    enc:v1: 前缀 + 域隔离 + 幂等

算法、nonce 布局(前置 + io.ReadFull(rand))、密钥环轮换逻辑全都一样,
只有 Codec 多了前缀与域隔离。

危害不是"代码重复"这么轻:

  · 两套实现各自演化,任何一侧的改动不会被另一侧的判据发现
  · Store 缺域隔离 ⇒ 变量库与配置共用密钥(安全倒退)
  · Store 缺前缀 ⇒ 无法区分"旧密文"与"明文"(惰性迁移的障碍)

## 本次做的

### Store 委托 Codec

    codecOf()            按当前 keys 环惰性构建(轮换后自动跟上)
    sealWithRing()       新格式(enc:v1: 前缀)
    openWithStoreRing()  兼容新旧两种格式,返回 needsMigrate

删除 Store 自带的 seal/open/openWithRing —— 现在**只有一处** AES-GCM。

### 域隔离(安全判据)

    storeCodecDomain  = "security/variables"
    configCodecDomain = "config-at-rest"

两者必须不同:同域时一处明文泄漏可推导另一处密文。

### 存量密文惰性迁移

旧格式是裸 base64 无前缀,而 Codec.Open 对无前缀输入**原样返回明文**
(那是给 config 的存量明文兼容)。直接交给 Open 会把密文当明文返回,
症状是"凭据回填出一个 base64 串"。

所以 Store 走 openWithStoreRing:

    enc:v1:... → Codec.Open
    裸 base64  → Codec.OpenLegacy(解开后立刻回写新格式)

不做启动时全量迁移(21G 数据目录的教训:迁移窗口越长越危险),
也不让两种格式永久共存(判据永不能要求"落盘都是新格式")。

### 删 globalCodec 单例 → 归 Runtime

    security 模块 → rt.SetCodec(c) → ks.Security
    config 模块   → cfgReg.SetCodec(ks.Security.Codec())

ConfigRegistry 加 codec 字段(注入而非读全局),6 处 ConfigCodec() 改为
r.codecOf();PluginSettings 经 p.registry 转调。
sdk.SecretsAPI 也加 codec 参数(插件加密能力来自它的内核实例)。

### 顺带

  · InitConfigCodec* / ClearConfigCodec 删除,改 NewConfigCodec 返回实例
  · homed-key-rotate 改为 构造 + reg.SetCodec(不再装全局)
  · bootstrap_order_test 的锚点从 InitConfigCodecWithOldKeys 改为
    NewConfigCodec(守的不变量不变,只是生效点写法变了)

## 判据(均经变异验证)

  TestNoPackageLevelSingletons          禁表补入 globalCodec
  TestStoreWritesPrefixedCiphertext     新密文必须带 enc:v1:(旧实现裸 base64 ⇒ 红)
  TestStoreAndConfigUseDifferentDomains 域隔离;改成同域 ⇒ 红(实测确认)
  TestLegacyCiphertextStillReadableAndMigrates  旧格式可读 + 落盘已升级
  TestRotationKeepsOldCiphertextReadable        轮换后旧条目仍可回填

## 验证

  go build ./...              PASS
  go vet ./...                PASS
  gofmt -l                    干净
  go test ./... -count=1      63 包全过,0 FAIL
  干净检出(git worktree)     build + security/config 测试全绿

## 数据风险

加密实现切换有丢数据风险,因此:
  · 先写往返判据,再改实现
  · 惰性迁移(读到才升级),不做启动全量重写
  · 旧格式与旧密钥环**都保留**读取路径
2026-11-04 12:22:08 +08:00

118 lines
4.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package webui
// 判据:**Secret 标志必须活着到达 WebUI 的 meta**。
//
// 由来:SDK 的 ConfigDef 一直有 Secret 字段,但内核侧三处转换
// (settingsImpl.RegisterDef / Defs / mapDefs)全部漏掉了它 ——
// 插件声明了 secret,前端拿到的 meta 里却没有这个标记,
// 于是敏感项被渲染成普通文本框明文回显。
//
// 这条判据钉住「声明 → meta」这一段,防止再次被漏掉。
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
internalConfig "github.com/JianFeeeee/HologramAgent/internal/config"
internalSDK "github.com/JianFeeeee/HologramAgent/internal/sdk"
)
func TestSecretFlagReachesSettingsMeta(t *testing.T) {
dir := t.TempDir()
reg := internalConfig.NewConfigRegistry(dir + "/config.db")
reg.SetCodec(internalConfig.NewTestCodec(t))
defer reg.Close()
// 插件用**两种写法**各声明一个敏感项
sett := internalSDK.NewSettings("secplug", reg)
sett.RegisterDef(internalSDK.ConfigDef{
Key: "by_flag", Type: "string", DisplayName: "标志式", Secret: true,
})
sett.RegisterDef(internalSDK.ConfigDef{
Key: "by_type", Type: "password", DisplayName: "类型式",
})
// 走真实 HTTP 处理器
h := &Handler{settings: internalSDK.NewSettings("webui", reg)}
req := httptest.NewRequest(http.MethodGet, "/api/settings?prefix=plugin.secplug", nil)
w := httptest.NewRecorder()
h.handleSettings(w, req)
if w.Code != http.StatusOK {
t.Fatalf("状态码 %d: %s", w.Code, w.Body.String())
}
var body struct {
Meta map[string]map[string]interface{} `json:"meta"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatalf("解析响应失败: %v", err)
}
byFlag, ok := body.Meta["plugin.secplug.by_flag"]
if !ok {
t.Fatalf("meta 里没有 by_flag;实际键: %v", keysOfMeta(body.Meta))
}
if byFlag["secret"] != true {
t.Errorf("Secret:true 未传递到 meta(前端会明文回显): %v", byFlag)
}
byType, ok := body.Meta["plugin.secplug.by_type"]
if !ok {
t.Fatalf("meta 里没有 by_type;实际键: %v", keysOfMeta(body.Meta))
}
if byType["type"] != "password" {
t.Errorf("password 类型应保持: %v", byType)
}
}
func keysOfMeta(m map[string]map[string]interface{}) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
return out
}
// 判据:敏感项在 WebUI 列表里的默认值**必须屏蔽**(E-3),
// 单键 reveal 才能看到明文;磁盘上仍是密文。
func TestSecretPlainInUIButCipherOnDisk(t *testing.T) {
dir := t.TempDir()
reg := internalConfig.NewConfigRegistry(dir + "/config.db")
reg.SetCodec(internalConfig.NewTestCodec(t))
defer reg.Close()
sett := internalSDK.NewSettings("webui", reg)
sett.RegisterDef(internalSDK.ConfigDef{Key: "apikey", Type: "password"})
if err := sett.Set("apikey", "ui-visible-secret-123456"); err != nil {
t.Fatal(err)
}
h := &Handler{settings: internalSDK.NewSettings("webui", reg)}
req := httptest.NewRequest(http.MethodGet, "/api/settings?prefix=plugin.webui", nil)
w := httptest.NewRecorder()
h.handleSettings(w, req)
if strings.Contains(w.Body.String(), "ui-visible-secret-123456") {
t.Fatal("E-3:设置列表不应回显敏感明文")
}
if !strings.Contains(w.Body.String(), SecretPlaceholder) {
t.Fatal("设置列表应显示敏感值占位符")
}
// 显式揭示仍可核对(单键、当前 WebUI 插件范围)。
reveal := httptest.NewRecorder()
h.handleSettingsReveal(reveal, httptest.NewRequest(http.MethodGet, "/api/settings/reveal?key=plugin.webui.apikey", nil))
if reveal.Code != http.StatusOK || !strings.Contains(reveal.Body.String(), "ui-visible-secret-123456") {
t.Fatalf("显式 reveal 应返回当前插件的明文: status=%d body=%s", reveal.Code, reveal.Body.String())
}
var raw string
if err := reg.DB().QueryRow(
`SELECT value FROM config_webui WHERE key='apikey'`).Scan(&raw); err != nil {
t.Fatal(err)
}
if strings.Contains(raw, "ui-visible-secret") {
t.Errorf("磁盘上不应有明文: %q", raw)
}
}