mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-11-06 09:17:31 +00:00
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 测试全绿
## 数据风险
加密实现切换有丢数据风险,因此:
· 先写往返判据,再改实现
· 惰性迁移(读到才升级),不做启动全量重写
· 旧格式与旧密钥环**都保留**读取路径
This commit is contained in:
@ -31,7 +31,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// EncPrefixV1 是密文的自描述前缀。
|
||||
@ -180,6 +179,75 @@ func (c *Codec) Open(stored string) (string, error) {
|
||||
return "", fmt.Errorf("%w (域 %s)", ErrBadCiphertext, c.Domain())
|
||||
}
|
||||
|
||||
// NewLegacyRingCodec 构造一个用**现成密钥环**(不做域派生)的编解码器。
|
||||
//
|
||||
// ★ 专供 Store 使用(2026-11-04 T3.2)。与 NewCodec 的区别只有一点:
|
||||
//
|
||||
// NewCodec :用一个主密钥 HMAC 派生出**该域**的子密钥
|
||||
// NewLegacyRingCodec:直接吃一组密钥(Store 的 keys 环,含历史代)
|
||||
//
|
||||
// 为什么 Store 不能走 NewCodec 的域派生:它的密文是**用主密钥本身**加密的
|
||||
// (历史数据),换成派生密钥会让所有存量条目解不开 —— 那是数据丢失,
|
||||
// 不是迁移。
|
||||
//
|
||||
// keys[0] 是当前加密钥,其余只用于 Open(轮换过渡期)。
|
||||
func NewLegacyRingCodec(domain string, keys [][]byte) *Codec {
|
||||
c := &Codec{domain: domain}
|
||||
if len(keys) > 0 && len(keys[0]) == 32 {
|
||||
c.key = keys[0]
|
||||
for _, k := range keys[1:] {
|
||||
if len(k) == 32 {
|
||||
c.oldKeys = append(c.oldKeys, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// OpenLegacy 解开**无前缀**的旧格式密文(裸 base64 + nonce 前置)。
|
||||
//
|
||||
// ★ 为什么必须单独一个方法而不是让 Open 兼容:
|
||||
//
|
||||
// `Open` 对无前缀输入**原样返回**(那是"存量明文兼容"的正确行为——
|
||||
// 老配置里存的就是明文)。但 Store 的旧密文恰好也是无前缀的裸 base64,
|
||||
// 两者在字面上无法区分。
|
||||
//
|
||||
// 所以:
|
||||
//
|
||||
// 配置(config)→ 用 Open:无前缀 = 明文,原样返回
|
||||
// 变量库(Store)→ 读到无前缀时先试 OpenLegacy:能解开 = 旧密文
|
||||
// ⇒ 立刻用 Seal 回写为新格式(惰性迁移)
|
||||
//
|
||||
// 把歧义留在**调用方**(它知道自己存的是什么),而不是让 Open 猜。
|
||||
func (c *Codec) OpenLegacy(stored string) (string, error) {
|
||||
if !c.Enabled() {
|
||||
return "", fmt.Errorf("%w: 有密文但编解码器未启用(域 %s)", ErrNoMasterKey, c.Domain())
|
||||
}
|
||||
raw, err := decodeB64(stored)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: 旧格式 base64 解码失败", ErrBadCiphertext)
|
||||
}
|
||||
keys := append([][]byte{c.key}, c.oldKeys...)
|
||||
for _, k := range keys {
|
||||
block, err := aes.NewCipher(k)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if len(raw) < gcm.NonceSize() {
|
||||
continue
|
||||
}
|
||||
plain, err := gcm.Open(nil, raw[:gcm.NonceSize()], raw[gcm.NonceSize():], nil)
|
||||
if err == nil {
|
||||
return string(plain), nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("%w: 旧格式密文解不开(域 %s)", ErrBadCiphertext, c.Domain())
|
||||
}
|
||||
|
||||
// IsEncrypted 报告一个已存储的值是否是本模块的密文。
|
||||
//
|
||||
// ★ 单调为真:密文解密后可能恰好以 `enc:v1:` 开头(极小概率),
|
||||
@ -188,38 +256,32 @@ func IsEncrypted(stored string) bool {
|
||||
return strings.HasPrefix(stored, EncPrefixV1)
|
||||
}
|
||||
|
||||
// ---------------- 全局配置编解码器 ----------------
|
||||
// ---------------- 配置落盘编解码器 ----------------
|
||||
|
||||
var (
|
||||
globalCodecMu sync.RWMutex
|
||||
globalCodec *Codec
|
||||
)
|
||||
// ★ 2026-11-04(T3.2):包级单例 `globalCodec` 与访问器 `ConfigCodec()`
|
||||
// 已删除(用户裁定「所有共享数据统一挂载一个 kernel 提供的挂载点上暴露」)。
|
||||
//
|
||||
// 配置加密器现在归 `security.Runtime`:
|
||||
//
|
||||
// security 模块装配 → rt.SetCodec(c) → ks.Security
|
||||
// config 模块装配 → cfgReg.SetCodec(ks.Security.Codec())
|
||||
//
|
||||
// 与变量库(ks.Security.Store())同源同生命周期,没有任何第二条通道。
|
||||
|
||||
// InitConfigCodec 装配配置落盘用的编解码器(内核启动时调用一次)。
|
||||
func InitConfigCodec(masterKey []byte) (*Codec, error) {
|
||||
return InitConfigCodecWithOldKeys(masterKey, nil)
|
||||
// NewConfigCodec 构造配置落盘用的编解码器(**不**注册任何全局状态)。
|
||||
//
|
||||
// 当前钥负责 Seal;旧钥仅参与 Open(E-1 平滑轮换)。
|
||||
// 调用方拿到实例后负责注入(见 Runtime.SetCodec)。
|
||||
func NewConfigCodec(masterKey []byte, oldKeys [][]byte) (*Codec, error) {
|
||||
return NewCodecWithOldKeys(masterKey, configCodecDomain, oldKeys)
|
||||
}
|
||||
|
||||
// InitConfigCodecWithOldKeys 装配支持 E-1 平滑轮换的配置 codec。
|
||||
// 当前钥负责 Seal;旧钥仅参与 Open。
|
||||
|
||||
func InitConfigCodecWithOldKeys(masterKey []byte, oldKeys [][]byte) (*Codec, error) {
|
||||
c, err := NewCodecWithOldKeys(masterKey, "config-at-rest", oldKeys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
globalCodecMu.Lock()
|
||||
globalCodec = c
|
||||
globalCodecMu.Unlock()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// ConfigCodec 取配置编解码器;未装配时返回 nil(调用方原样读写)。
|
||||
func ConfigCodec() *Codec {
|
||||
globalCodecMu.RLock()
|
||||
defer globalCodecMu.RUnlock()
|
||||
return globalCodec
|
||||
}
|
||||
// configCodecDomain 是配置落盘加密的域。
|
||||
//
|
||||
// ★ 必须与变量库的域(storeCodecDomain)不同 —— 见那边的说明。
|
||||
// 域在这里集中定义,避免"两处各写一个字符串"(拼错了不会报错,
|
||||
// 只会让两个域意外重合,而那是安全倒退)。
|
||||
const configCodecDomain = "config-at-rest"
|
||||
|
||||
// NeedsRekey 报告该密文是否**不是**当前主密钥加的(即轮换后尚未重加密)。
|
||||
//
|
||||
@ -273,13 +335,11 @@ func (c *Codec) openWithSingleKey(key []byte, stored string) (string, error) {
|
||||
return string(plain), nil
|
||||
}
|
||||
|
||||
// ClearConfigCodec 卸下配置编解码器(测试与"显式关闭加密"用)。
|
||||
// ★ 2026-11-04:`ClearConfigCodec` 已删除。
|
||||
//
|
||||
// 单独一个函数而不是让 InitConfigCodec(nil) 承担:
|
||||
// 后者语义模糊(nil 是"没密钥"还是"要清空"?),且会掩盖调用方的错误
|
||||
// —— 曾因此让一个判据假绿(以为清空了,其实上一把密钥还在)。
|
||||
func ClearConfigCodec() {
|
||||
globalCodecMu.Lock()
|
||||
globalCodec = nil
|
||||
globalCodecMu.Unlock()
|
||||
}
|
||||
// 它清的是包级单例。现在"关闭加密"通过不注入(或注入 nil)表达:
|
||||
//
|
||||
// rt.SetCodec(nil) → config.codecOf() == nil
|
||||
// cfgReg.SetCodec(nil)
|
||||
//
|
||||
// 比"清空一个全局变量"更明确:状态属于对象,不属于进程。
|
||||
|
||||
216
internal/security/codec_unify_test.go
Normal file
216
internal/security/codec_unify_test.go
Normal file
@ -0,0 +1,216 @@
|
||||
package security
|
||||
|
||||
// 判据:**加密能力只有一处实现**(2026-11-04 T3.2)。
|
||||
//
|
||||
// ## 用户裁定
|
||||
//
|
||||
// > 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 写入的密文必须带 enc:v1: 前缀(旧实现是裸 base64)
|
||||
// ② 变量库与配置**不得同域**(同域 = 一处泄漏可推导另一处)
|
||||
// ③ 旧格式(裸 base64)密文必须仍可读,且读到后就地升级
|
||||
// ④ 密钥轮换后旧密文仍可解(不能因换实现而丢数据)
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestStoreWritesPrefixedCiphertext 钉住 ①:新写入必须带前缀。
|
||||
//
|
||||
// 变红条件:把 Store.Put 改回自建 seal(裸 base64)⇒ 红。
|
||||
func TestStoreWritesPrefixedCiphertext(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s, err := MustStore(Options{
|
||||
Path: filepath.Join(dir, "v.json"),
|
||||
KeyFn: func() ([]byte, error) { return []byte("0123456789abcdef0123456789abcdef"), nil },
|
||||
Enabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("MustStore: %v", err)
|
||||
}
|
||||
if _, err := s.Submit("ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "test"); err != nil {
|
||||
t.Fatalf("Submit: %v", err)
|
||||
}
|
||||
|
||||
// 从内存里读原始密文(绕过解密)。
|
||||
s.mu.RLock()
|
||||
var sealed string
|
||||
for _, e := range s.data {
|
||||
sealed = e.Sealed
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
|
||||
if sealed == "" {
|
||||
t.Fatal("没读出密文")
|
||||
}
|
||||
if !IsEncrypted(sealed) {
|
||||
t.Fatalf("★ Store 写入的密文没有 %q 前缀 —— 说明它还在用自建 seal。\n"+
|
||||
"加密必须委托 Codec(用户裁定:「store 也应该调用 security 的加密能力」)。\n"+
|
||||
"实际前缀(前 24 字符): %q", EncPrefixV1, sealed[:min(24, len(sealed))])
|
||||
}
|
||||
}
|
||||
|
||||
// TestStoreAndConfigUseDifferentDomains 钉住 ②:域隔离(**安全判据**)。
|
||||
//
|
||||
// 变红条件:把 storeCodecDomain 改成与 configCodecDomain 相同 ⇒ 红。
|
||||
//
|
||||
// 为什么这条必须有:同域意味着"用同一把密钥派生同一把子密钥加密两处不同
|
||||
// 用途的数据"。一旦变量库的明文泄漏,它就成为配置密文的字典攻击素材。
|
||||
// 这是安全倒退,不是风格问题。
|
||||
func TestStoreAndConfigUseDifferentDomains(t *testing.T) {
|
||||
if storeCodecDomain == configCodecDomain {
|
||||
t.Fatalf("★ 变量库与配置用了同一个加密域 %q\n\n"+
|
||||
"两者必须不同域:同域时一处明文泄漏可推导另一处密文。\n"+
|
||||
"storeCodecDomain=%q configCodecDomain=%q",
|
||||
storeCodecDomain, storeCodecDomain, configCodecDomain)
|
||||
}
|
||||
// 更强的判据:实际用同一把主密钥构造两个 codec,密文必须互不可解。
|
||||
const key = "0123456789abcdef0123456789abcdef"
|
||||
storeCodec := NewLegacyRingCodec(storeCodecDomain, [][]byte{[]byte(key)})
|
||||
cfgCodec, err := NewConfigCodec([]byte(key), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewConfigCodec: %v", err)
|
||||
}
|
||||
|
||||
sealedByStore, err := storeCodec.Seal("same-plaintext")
|
||||
if err != nil {
|
||||
t.Fatalf("store Seal: %v", err)
|
||||
}
|
||||
if plain, oerr := cfgCodec.Open(sealedByStore); oerr == nil {
|
||||
t.Fatalf("★ 配置 codec 解开了变量库的密文(明文 %q)—— 域隔离失效", plain)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyCiphertextStillReadableAndMigrates 钉住 ③:旧格式可读 + 惰性迁移。
|
||||
//
|
||||
// 变红条件:
|
||||
// - openWithStoreRing 不兼容无前缀格式 ⇒ 旧数据全丢(红)
|
||||
// - 读到旧格式后不回写 ⇒ 文件里仍是旧格式(红)
|
||||
func TestLegacyCiphertextStillReadableAndMigrates(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
const key = "0123456789abcdef0123456789abcdef"
|
||||
path := filepath.Join(dir, "v.json")
|
||||
|
||||
// ① 用**旧格式**(裸 base64,无前缀)造一条密文 —— 模拟 T3.2 之前的数据。
|
||||
legacyCodec := NewLegacyRingCodec(storeCodecDomain, [][]byte{[]byte(key)})
|
||||
legacySealed, err := legacyCodec.Seal("ghp_LEGACY_TOKEN_0123456789")
|
||||
if err != nil {
|
||||
t.Fatalf("Seal: %v", err)
|
||||
}
|
||||
// Seal 带前缀;去掉它才是真正的旧格式(裸 base64)。
|
||||
oldFormat := strings.TrimPrefix(legacySealed, EncPrefixV1)
|
||||
if IsEncrypted(oldFormat) {
|
||||
t.Fatal("构造旧格式失败(仍有前缀)")
|
||||
}
|
||||
|
||||
// ② 写一份带旧格式条目的库文件。
|
||||
s, err := MustStore(Options{
|
||||
Path: path,
|
||||
KeyFn: func() ([]byte, error) { return []byte(key), nil },
|
||||
Enabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("MustStore: %v", err)
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.data["sec_legacy01"] = &Entry{Alias: "sec_legacy01", Sealed: oldFormat, Source: "intercepted"}
|
||||
if err := s.saveLocked(); err != nil {
|
||||
t.Fatalf("saveLocked: %v", err)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
// ③ 重新加载后必须能**解开**旧格式(否则旧数据全丢)。
|
||||
s2, err := MustStore(Options{
|
||||
Path: path,
|
||||
KeyFn: func() ([]byte, error) { return []byte(key), nil },
|
||||
Enabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("重新加载: %v", err)
|
||||
}
|
||||
plain, n, _ := s2.Fill("token=@{sec_legacy01}")
|
||||
if n != 1 {
|
||||
t.Fatalf("★ 旧格式密文解不开(回填 0 处)—— 存量数据全丢。实际: %q", plain)
|
||||
}
|
||||
if !strings.Contains(plain, "ghp_LEGACY_TOKEN") {
|
||||
t.Fatalf("回填结果不对: %q", plain)
|
||||
}
|
||||
|
||||
// ④ 惰性迁移:读到旧格式后,落盘应升级为新格式。
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("读落盘文件: %v", err)
|
||||
}
|
||||
if strings.Contains(string(raw), oldFormat) {
|
||||
t.Fatalf("★ 旧格式密文仍留在磁盘上 —— 惰性迁移没有回写。\n" +
|
||||
"两种格式永久共存会让'落盘都是新格式'这类判据永远无法成立。")
|
||||
}
|
||||
if !strings.Contains(string(raw), EncPrefixV1) {
|
||||
t.Fatalf("迁移后应出现 %q 前缀,实际文件内容(前 200 字符): %s",
|
||||
EncPrefixV1, string(raw[:min(200, len(raw))]))
|
||||
}
|
||||
}
|
||||
|
||||
// TestRotationKeepsOldCiphertextReadable 钉住 ④:轮换后旧密文仍可解。
|
||||
//
|
||||
// 变红条件:RotateKey 只保留新钥、丢掉旧钥 ⇒ 旧条目全变"解不开"。
|
||||
func TestRotationKeepsOldCiphertextReadable(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
oldKey := []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
|
||||
newKey := []byte("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
|
||||
|
||||
path := filepath.Join(dir, "v.json")
|
||||
s, err := MustStore(Options{
|
||||
Path: path,
|
||||
KeyFn: func() ([]byte, error) { return oldKey, nil },
|
||||
Enabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("MustStore: %v", err)
|
||||
}
|
||||
alias, err := s.Submit("ghp_ROTATE_ME_0123456789", "test")
|
||||
if err != nil {
|
||||
t.Fatalf("Submit: %v", err)
|
||||
}
|
||||
|
||||
// 轮换到新钥(旧钥进历史环)。
|
||||
if err := s.RotateKey(newKey); err != nil {
|
||||
t.Fatalf("RotateKey: %v", err)
|
||||
}
|
||||
|
||||
// 轮换后必须仍能回填(否则所有历史 @{sec_xxx} 失效)。
|
||||
out, n, _ := s.Fill("token=@{" + alias + "}")
|
||||
if n != 1 || !strings.Contains(out, "ghp_ROTATE_ME") {
|
||||
t.Fatalf("★ 轮换后旧条目解不开(回填 %d 处): %q\n"+
|
||||
"这会静默作废所有历史引用 —— 用户看到的是一次凭据替换失败。", n, out)
|
||||
}
|
||||
}
|
||||
|
||||
// min 是 Go 版本早于 1.21 时的兜底(本仓支持较老工具链)。
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@ -76,6 +76,16 @@ type Runtime struct {
|
||||
// 是**插件声明出来的注册表**,每个 agent 各持一份就会变成
|
||||
// “插件往 A 声明了档位,B 看不见”—— 那是最难查的一类缺陷。
|
||||
// 所以切分是「共享注册表 + per-agent 执行视图」。
|
||||
// codec 是配置落盘加密执行者(独立域,与变量库不共用密钥派生)。
|
||||
//
|
||||
// ★ 2026-11-04(T3.2):此前是包级单例 `globalCodec`(ConfigCodec())。
|
||||
// 那个单例绕开了内核统一挂载点,且让"哪个 codec 生效"取决于
|
||||
// "最后谁调了 InitConfigCodec"。
|
||||
//
|
||||
// 现在它归 Runtime:config 模块从 ks.Security.Codec() 取,
|
||||
// 与变量库(ks.Security.Store())同源同生命周期。
|
||||
codec *Codec
|
||||
|
||||
scopesByAgent map[string]*AgentScope
|
||||
scopeMu sync.Mutex
|
||||
}
|
||||
@ -167,6 +177,26 @@ func (r *Runtime) FillForExecution(ins Inspection, text string) (string, int) {
|
||||
return r.gate.FillForExecution(ins, text)
|
||||
}
|
||||
|
||||
// Codec 返回配置落盘加密器(未装配时为 nil)。
|
||||
//
|
||||
// ★ 与 Store() 的区别:Store 管**凭据别名**(@{sec_xxx}),
|
||||
// Codec 管**配置项密文**(enc:v1:...)。两者是独立的密钥域,
|
||||
// 同一把主密钥派生出的不同子密钥 —— 域隔离是安全要求。
|
||||
func (r *Runtime) Codec() *Codec {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
return r.codec
|
||||
}
|
||||
|
||||
// SetCodec 注入配置加密器(安全模块装配时调用)。
|
||||
func (r *Runtime) SetCodec(c *Codec) {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
r.codec = c
|
||||
}
|
||||
|
||||
// Store 返回底层变量库(安全工具族 secret_* 需要元信息)。
|
||||
func (r *Runtime) Store() *Store {
|
||||
if r == nil || r.gate == nil {
|
||||
|
||||
@ -51,15 +51,16 @@ import (
|
||||
//
|
||||
// 每一条都对应一次真实事故或一次可复现的错配:
|
||||
//
|
||||
// global → 变量库:测试装单例、代码用 agent 字段,测的与跑的不是同一份
|
||||
// runtime → 防火墙:多实例时被覆盖
|
||||
// global → 变量库:测试装单例、代码用 agent 字段,测的与跑的不是同一份
|
||||
// runtime → 防火墙:多实例时被覆盖
|
||||
// globalCodec → 配置加密:域隔离失效的隐患(T3.2 已删)
|
||||
//
|
||||
// ★ globalCodec 不在本表 —— 它属于 T3.2(Store 复用 Codec + Codec 归 Runtime)。
|
||||
// 那条改动还牵涉 config 的 6 个调用点与惰性密文迁移,单独一步做。
|
||||
// 本判据只钉已经完成的部分,避免"半成品状态让整套判据长期红"
|
||||
// (长期红的判据会被人习惯性忽略,那时它就等于不存在)。
|
||||
// ★ 三条全部落地后才纳入本表。
|
||||
//
|
||||
// - 半成品状态就纳入 ⇒ 判据长期红 ⇒ 被人习惯性忽略 ⇒ 等于不存在
|
||||
// - 全部落定后仍不纳入 ⇒ 后来者能原样加回来
|
||||
func forbiddenPackageLevelVars() []string {
|
||||
return []string{"global", "runtime"}
|
||||
return []string{"global", "runtime", "globalCodec"}
|
||||
}
|
||||
|
||||
// TestNoPackageLevelSingletons 钉住本包不得声明这三个包级变量。
|
||||
|
||||
@ -104,6 +104,23 @@ type Store struct {
|
||||
// —— 因为新密文是按新钥加密的,两者必须同时可读才能平滑迁移。
|
||||
keys []keyGen
|
||||
|
||||
// codec 是加解密执行者(**唯一**的 AES-GCM 实现)。
|
||||
//
|
||||
// ★ 2026-11-04(T3.2):此前 Store 自带一份 seal/open 实现,
|
||||
// 与 Codec 是**两套重复的 AES-256-GCM**(算法、nonce 布局、密钥环
|
||||
// 逻辑全都一样,只是 Codec 多了 enc:v1: 前缀与域隔离)。
|
||||
//
|
||||
// 用户裁定:
|
||||
//
|
||||
// > store也应该调用security的加密能力!
|
||||
//
|
||||
// 现在 Store 只做"我用哪个域、我的密钥环是什么",加解密一律委托。
|
||||
// 这让"加密算法只有一处实现",也修掉一个真实隐患:
|
||||
// 两套实现曾在 nonce 布局上各自演化(一处前置、一处也前置但无前缀),
|
||||
// 任何一侧改动都不会被另一侧的判据发现。
|
||||
codec *Codec
|
||||
codecMu sync.Mutex // 保护 codec 的惰性重建(keys 环在轮换时会变)
|
||||
|
||||
// enabled 支持显式关闭(本仓「显式才是特权」)。
|
||||
enabled bool
|
||||
|
||||
@ -250,13 +267,9 @@ func (s *Store) Alias(plain string) (string, error) {
|
||||
// 别名若随新主密钥改变,记忆/上下文里的旧 @{sec_...} 会失效,
|
||||
// 且同一个凭据会出现两份变量。先在现有条目中按密钥环解密比对;
|
||||
// 找到就复用旧别名,找不到才用当前钥派生新别名。
|
||||
cands := s.keysForDecrypt()
|
||||
if len(cands) == 0 {
|
||||
cands = [][]byte{key}
|
||||
}
|
||||
s.mu.RLock()
|
||||
for alias, e := range s.data {
|
||||
if got, openErr := openWithRing(cands, e.Sealed); openErr == nil && got == plain {
|
||||
if got, _, openErr := s.openWithStoreRing(e.Sealed); openErr == nil && got == plain {
|
||||
s.mu.RUnlock()
|
||||
return alias, nil
|
||||
}
|
||||
@ -302,21 +315,16 @@ func (s *Store) keysForDecrypt() [][]byte {
|
||||
//
|
||||
// ★ 为何不是“记录每条密文属于哪一代”:那需要**改 Entry 结构**(加世代字段),
|
||||
// 而密文本身已经能被正确的那把钥唯一解开(AES-GCM 带认证)。
|
||||
// 逐个尝试的成本是常数级(代数量 <= 2 是常态),换来的是**零 schema 迁移**。
|
||||
func openWithRing(cands [][]byte, sealed string) (string, error) {
|
||||
if len(cands) == 0 {
|
||||
return "", ErrNoMasterKey
|
||||
}
|
||||
var lastErr error
|
||||
for _, k := range cands {
|
||||
plain, err := open(k, sealed)
|
||||
if err == nil {
|
||||
return plain, nil
|
||||
}
|
||||
lastErr = err
|
||||
}
|
||||
return "", lastErr
|
||||
}
|
||||
// ★ 2026-11-04(T3.2):`openWithRing` / `seal` / `open` 已删除。
|
||||
//
|
||||
// 它们是 Store 自带的 AES-GCM 实现,与 Codec 完全重复(算法、nonce 布局、
|
||||
// 密钥环逻辑一致,只是 Codec 多了 enc:v1: 前缀与域隔离)。
|
||||
//
|
||||
// 现在唯一的实现是 Codec:
|
||||
//
|
||||
// 写入 → s.sealWithRing(新格式,带前缀)
|
||||
// 读取 → s.openWithStoreRing(兼容新旧两种格式)
|
||||
// 轮换 → NewLegacyRingCodec(old) 解 + NewLegacyRingCodec(new) 加密
|
||||
|
||||
// RotateKey 平滑轮换变量库主密钥,并保持**已有别名不变**。
|
||||
//
|
||||
@ -341,13 +349,26 @@ func (s *Store) RotateKey(newKey []byte) error {
|
||||
if len(oldCandidates) == 0 {
|
||||
return ErrNoMasterKey
|
||||
}
|
||||
// 旧环解、新钥加密。
|
||||
//
|
||||
// ★ 这里刻意**不用** s.openWithStoreRing:它读 s.keys,而此刻
|
||||
// s.keys 还没换(下面才换)—— 但语义上要明确"用旧环解",
|
||||
// 所以显式构造。
|
||||
oldCodec := NewLegacyRingCodec(storeCodecDomain, oldCandidates)
|
||||
newCodec := NewLegacyRingCodec(storeCodecDomain, [][]byte{newKey})
|
||||
copyData := make(map[string]*Entry, len(s.data))
|
||||
for alias, e := range s.data {
|
||||
plain, err := openWithRing(oldCandidates, e.Sealed)
|
||||
if err != nil {
|
||||
return fmt.Errorf("security: 轮换时解密变量 %s 失败,未切换密钥: %w", alias, err)
|
||||
var plain string
|
||||
var oerr error
|
||||
if IsEncrypted(e.Sealed) {
|
||||
plain, oerr = oldCodec.Open(e.Sealed)
|
||||
} else {
|
||||
plain, oerr = oldCodec.OpenLegacy(e.Sealed)
|
||||
}
|
||||
sealed, err := seal(newKey, plain)
|
||||
if oerr != nil {
|
||||
return fmt.Errorf("security: 轮换时解密变量 %s 失败,未切换密钥: %w", alias, oerr)
|
||||
}
|
||||
sealed, err := newCodec.Seal(plain)
|
||||
if err != nil {
|
||||
return fmt.Errorf("security: 轮换时加密变量 %s 失败,未切换密钥: %w", alias, err)
|
||||
}
|
||||
@ -369,6 +390,69 @@ func (s *Store) RotateKey(newKey []byte) error {
|
||||
|
||||
// ---------------- 加密 ----------------
|
||||
|
||||
// codecOf 返回当前密钥环对应的编解码器(惰性构建)。
|
||||
//
|
||||
// ★ 为什么惰性而不是构造期建一次:`keys` 环会在 `RotateKey` 里变化
|
||||
// (新钥插到头部),那时旧 codec 的 key 就过期了 —— 表现为"轮换后
|
||||
// 新写入的条目用旧钥加密",而轮换的**全部意义**就是尽快停用旧钥。
|
||||
// 每次取用都按当前环重建,代价是一次切片拷贝。
|
||||
func (s *Store) codecOf() *Codec {
|
||||
s.codecMu.Lock()
|
||||
defer s.codecMu.Unlock()
|
||||
keys := make([][]byte, 0, len(s.keys))
|
||||
for _, g := range s.keys {
|
||||
keys = append(keys, g.Key)
|
||||
}
|
||||
s.codec = NewLegacyRingCodec(storeCodecDomain, keys)
|
||||
return s.codec
|
||||
}
|
||||
|
||||
// storeCodecDomain 是变量库的加密域。
|
||||
//
|
||||
// ★ 必须与 config 的域**不同**:域隔离是安全要求,不是风格。
|
||||
// 同域意味着"用同一把密钥加密两处不同用途的数据",一旦某处的明文
|
||||
// 泄漏就能成为另一处的字典攻击素材。
|
||||
const storeCodecDomain = "security/variables"
|
||||
|
||||
// sealWithRing 用密钥环加密(新格式,带 enc:v1: 前缀)。
|
||||
func (s *Store) sealWithRing(plain string) (string, error) {
|
||||
c := s.codecOf()
|
||||
if !c.Enabled() {
|
||||
return "", ErrNoMasterKey
|
||||
}
|
||||
return c.Seal(plain)
|
||||
}
|
||||
|
||||
// openWithStoreRing 解开一条条目密文,**兼容旧格式**。
|
||||
//
|
||||
// 返回 (明文, 是否需要迁移回写)。
|
||||
//
|
||||
// 两种格式:
|
||||
//
|
||||
// enc:v1:... → 新格式,Codec.Open
|
||||
// 裸 base64 → 旧格式(T3.2 之前写的),Codec.OpenLegacy
|
||||
//
|
||||
// ★ 为什么必须区分:`Codec.Open` 对无前缀输入**原样返回明文**
|
||||
// (那是给 config 的"存量明文兼容"用的)。而 Store 的旧密文恰好也
|
||||
// 无前缀 —— 直接交给 Open 会把密文当明文返回,症状是"凭据回填出一个
|
||||
// base64 串",看起来像数据损坏,实际是格式误判。
|
||||
func (s *Store) openWithStoreRing(sealed string) (plain string, needsMigrate bool, err error) {
|
||||
c := s.codecOf()
|
||||
if !c.Enabled() {
|
||||
return "", false, ErrNoMasterKey
|
||||
}
|
||||
if IsEncrypted(sealed) {
|
||||
p, oerr := c.Open(sealed)
|
||||
return p, false, oerr
|
||||
}
|
||||
// 无前缀:只可能是旧格式密文(Store 从不存明文)。
|
||||
p, oerr := c.OpenLegacy(sealed)
|
||||
if oerr != nil {
|
||||
return "", false, oerr
|
||||
}
|
||||
return p, true, nil
|
||||
}
|
||||
|
||||
func seal(key []byte, plain string) (string, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
@ -463,11 +547,9 @@ func (s *Store) Replace(text, where string, detect []Pattern) (string, []Evt) {
|
||||
//
|
||||
// 返回 merged=true 表示这是**合并到已有别名**(同变量合并能力)。
|
||||
func (s *Store) Put(alias, plain, source, note string) (merged bool, err error) {
|
||||
key, err := s.key()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
sealed, err := seal(key, plain)
|
||||
// ★ 2026-11-04(T3.2):写入走 Codec(带 enc:v1: 前缀),
|
||||
// 不再自建 seal。旧条目仍按旧格式可读(见 openWithStoreRing)。
|
||||
sealed, err := s.sealWithRing(plain)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@ -515,6 +597,46 @@ func (s *Store) Forget(alias string) error {
|
||||
return s.saveLocked()
|
||||
}
|
||||
|
||||
// migrateEntry 把一条旧格式条目就地升级为新格式(惰性迁移)。
|
||||
//
|
||||
// ## 为什么需要惰性迁移
|
||||
//
|
||||
// T3.2 之前 Store 写入的是**裸 base64**(无前缀)。切到 Codec 之后新写入
|
||||
// 带 `enc:v1:` 前缀,但磁盘上已有的条目仍是旧格式。
|
||||
//
|
||||
// 三条路可选:
|
||||
//
|
||||
// ① 不做迁移 —— 旧格式永远可读(openWithStoreRing 兼容),
|
||||
// 代价是"两种格式永久共存",判据永不能要求"落盘都是新格式"
|
||||
// ② 启动时全量迁移 —— 有停机风险(21G 数据目录的教训:迁移窗口越长越危险)
|
||||
// ③ 惰性迁移 —— 读到旧的就地升级,零停机、零额外扫描
|
||||
//
|
||||
// 选 ③。这是本仓已在用的手法(Codec.Rekey 同样是"用到了才升级")。
|
||||
//
|
||||
// ## 为什么失败不报错
|
||||
//
|
||||
// 迁移失败只影响"下次读时还要再解一次旧格式",不影响本次读取(明文已经
|
||||
// 在前一步拿到了)。为一处升级失败让整个回填失败,是把可恢复的降级变成
|
||||
// 不可恢复的中断。
|
||||
func (s *Store) migrateEntry(alias, sealed string, plain string) {
|
||||
newSealed, err := s.sealWithRing(plain)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if newSealed == sealed {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
if e, ok := s.data[alias]; ok && e.Sealed == sealed {
|
||||
e.Sealed = newSealed
|
||||
s.mu.Unlock()
|
||||
// 落盘失败也不报错:内存已升级,下次 Save 会带上。
|
||||
_ = s.saveLocked()
|
||||
return
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// ---------------- 核心:回填(别名 → 明文,插件入向用) ----------------
|
||||
|
||||
// Fill 把文本里的 `@{alias}` 换回明文(路由到插件前用)。
|
||||
@ -528,14 +650,7 @@ func (s *Store) Fill(text string) (string, int, []string) {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return text, 0, nil
|
||||
}
|
||||
cands := s.keysForDecrypt()
|
||||
if len(cands) == 0 {
|
||||
// 环为空时退回 keyFn(未用 New 构造的路径,如测试里 SetGlobal)
|
||||
if k, err := s.key(); err == nil {
|
||||
cands = [][]byte{k}
|
||||
}
|
||||
}
|
||||
if len(cands) == 0 {
|
||||
if len(s.keys) == 0 {
|
||||
return text, 0, nil
|
||||
}
|
||||
var used []string
|
||||
@ -552,10 +667,14 @@ func (s *Store) Fill(text string) (string, int, []string) {
|
||||
if !ok {
|
||||
return m // 未知别名:原样保留
|
||||
}
|
||||
plain, err := openWithRing(cands, e.Sealed)
|
||||
plain, needsMigrate, err := s.openWithStoreRing(e.Sealed)
|
||||
if err != nil {
|
||||
return m
|
||||
}
|
||||
if needsMigrate {
|
||||
// 惰性迁移:读到旧格式就地升级(失败静默,下次再试)。
|
||||
s.migrateEntry(alias, e.Sealed, plain)
|
||||
}
|
||||
n++
|
||||
used = append(used, alias)
|
||||
return plain
|
||||
|
||||
Reference in New Issue
Block a user