mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-11-06 09:17:31 +00:00
feat: 模块化内核(编译期依赖图定序)+ 密钥防火墙 + 插件三态生命周期 (#10)
* feat(kernel): 模块化内核 + 编译期依赖图定序
把单体 init 序列拆成「模块自声明依赖 + 编译期生成依赖图 + 运行期只读图」。
## 为什么
原 cmd/homed/main.go 里 17 步 init 是**手写顺序**,依赖关系只存在于
注释和人脑里。实测踩到的坑(见 docs/zh/kernel-modularization-design.md):
· nlp.defaultParser 被 initONNXParser 写、被 distiller 读,两者相距 60 行,
只靠 ticker 10min 才没炸(隐式依赖,无声明)
· 加一个模块要人肉找"该插在哪",插错的表现是运行期 nil 解引用
· 关停是 defer ks.CloseAll(),而热更新路径 os.Exit(42) **跳过 defer**
⇒ docStore/distiller/textMem 的 flush 全部丢失(每次热更新都发生)
## 怎么改
- internal/kernelboot/:KernelState(一个结构体收全部包级共享变量,字段
nil 安全)、Module 接口、graphfile(依赖图编解码 + 与二进制 hash 对账)、
scheduler(按 BFS 层并行 Init)、syncbus(层边界写通知)、
lifecycle(Quiesce/Resume 可逆伪关机,区别于一次性 CloseAll)
- internal/kernelmod/<name>/:每个模块一个文件夹,Requires/Provides 自声明;
all/all.go 是唯一的 import 清单(Go 循环导入约束)
- cmd/homed-depgraph:编译期生成依赖图,Makefile 注入 digest
- 运行期只**读**图,不计算顺序(顺序是编译期决定的,源码里没有中央清单)
## 判据
kernelboot 8 条 + 图失败模式 7 条(全部拒绝并给准确错误)+ 模块目录数
与注册表一致性。变异测试 15/15 咬住,含:
· 删掉 AddCloser 的锁 → -race 报数据竞争
· Scheduler 同批跑去重 → 203 vs 200
· 图 hash 不匹配 → 拒绝启动
## 顺带修的缺陷
热更新路径漏调模块关闭 ⇒ 显式 stopKernelModules(),并用 AST 判据钉住
"必须在 os.Exit 之前"(字符串检查在本仓已骗过我三次)。
实测:冷启动 1630ms(5 层/17 模块,原 17 步串行);生产 22 插件全部建链。
* feat(security): 密钥防火墙 + 配置加密 + close 纪律
## 密钥防火墙
模型只见别名、不见明文;插件工具调用入口(StageHost.ExecuteTool)做入向
回填。三维能力:
· 出向:工具输出里的密钥被替换成 [[secret:name]] 别名后才进上下文
· 入向:模型传别名,入口处填回真值(插件完全无感知)
· 存储:config.db 里不存明文(0644 的库可读),敏感值独立 0600 文件
模式库「宁漏勿误伤」:宁可漏掉一次替换,也不把正常文本误当密钥。
## 配置加密
- internal/security/{codec,key,keyring,store,global}.go:AES-256-GCM,
enc:v1: 前缀,密钥轮换(OldKeys 解码 + 新钥加密)
- harden.go:数据目录权限收紧
- embedded.go:支持内嵌主密钥(可选,仍保留外部 key 文件路径)
- EncryptExistingSecrets / AuditSecrets:启动时幂等迁移 + 审计
## close 纪律(用户明确要求:只要调 close 就要有前置检查)
internal/safeclose:Safe / SafeFunc。全仓 37 处裸 close(chan) → 0。
关键教训(都写进注释和判据):
· `select { case <-ch: default: close(ch) }` **不是**并发安全的
(两个 goroutine 可同时命中 default)—— healthcheck 原先是这种写法
· `sync.Once` **不可重入**:X.Do(func(){ Safe(&X, ...) }) 会自锁,
症状是 go test 直接挂住(3 个包 600s 超时),栈里只有嵌套的 Once.Do
· map 里按请求持有的 channel(mcp/stdio.go、clawhubadapter/sidecar.go)
改成 *pendingRPC 包装,每通道一个 once
## 判据
security 全量 + TestNoBareCloseOutsideSafeclose(AST 级扫描,含注释剥离)
+ TestNoNestedSelfOnceDeadlock(正则修正:\w+ 不匹配点号,捕获组要含 '.')。
变异 2/2 咬住。全量 52 包 ok。
* feat(plugin+deploy): 插件三态生命周期、数据目录迁移、发行包修复
## 插件三态生命周期(用户要求:自动启动 / 启用但不自动启动 / 禁用)
- Manifest 新增 requires_facilities / auto_start(*bool,用于区分
"未声明"与"显式 false")
- plugin-host 模块(internal/kernelmod/pluginhost):用 kernelboot.Scheduler
按依赖时机拉起,**不再手写两阶段**
- 运行态停启 StopPlugin/StartPlugin **可逆**:不写 disabled_plugins
(不改用户决定)、不置 shuttingDown(之后还能加载)、会摘掉注册面
- 与 StopAll 的区别写进注释 —— StopAll 置 shuttingDown 后**永久无法加载**,
那是进程退出用的,误用于"暂停"就是关了就死
## 数据目录迁移(伪关机 → 迁移 → 唤醒)
- kernelboot/lifecycle.go:Quiesce/Resume(可逆,区别于一次性 CloseAll),
逆序暂停、逆序恢复、Pause 失败回滚
- kernelboot/migrate.go:BeginMigration/End 编排(先停插件 → 再停内核写者
→ 等在途归零)
- distiller/textmem 增 Pause/Resume 门(不是 cancel —— cancel 不可逆,
恢复要重建整个对象)
- 模块 migration:体检 + 生成可执行迁移脚本
★ 迁移脚本的三个实测教训(都写成了判据):
1. 无条件改 /etc/systemd/system ⇒ 演练把**生产** -data 改成了演练目录。
加 --dry-run(零改动)+ 强制校验 systemd 当前 -data == OLD
2. 本机没装 rsync,脚本在"服务已停、数据未搬"处硬失败 ⇒ cp -a 回退,
并明确警告不保硬链接/ACL(生产 plugindev 有大量 git 硬链接)
## 发行包修复(全部经实测确认)
1. package-linux.sh **完全漏打 depgraph.bin** ⇒ 内核 exit 1
("生产构建(内嵌 hash 非空)但读不到依赖图")
2. build_homed 不走 Makefile ⇒ 单独修 Makefile 无效,必须同时生成图+注入
3. build.sh 的 LDFLAGS 用**历史模块路径 gitcode.com** ⇒ -X 静默 no-op
⇒ --version 显示 unknown
4. Makefile -ldflags 用**单引号** ⇒ 注入了字面 $GRAPH_HASH
## ★ build.sh 的版本号必须校验(真实事故)
原 `VERSION="$(git describe --tags --dirty)"`。无 tag 分支上它返回**分支名**
`backup/pre-identity-rewrite-20261005-51-g03d87a4e-dirty`,被注入 meta.Version
⇒ 插件握手判据 MajorVersion() 把整串当主版本 ⇒ **22 个子进程插件全部
握手失败**("主版本不匹配")。内核活着、systemd active、日志每条都像
插件的问题 —— 实际是发行包带着非法版本号。
修法:git describe 只在形如 vX.Y.Z 时采用,否则回退 meta.Version(权威源),
并对最终值做形态守卫。deploy/packaging/version_guard_test.go 3 条判据,
变异 2/2 咬住。
## deb 的 systemd unit 改为 guard 模式
ExecStart=/usr/bin/homed --role=guard --data /var/lib/homeagent
(worker exit 42 → guard 重拉,不经过 systemd、不计失败)
含 RestartSteps/RestartMaxDelaySec/TimeoutStopSec + 硬化
(NoNewPrivileges/ProtectSystem/ProtectHome/DevicePolicy/ReadWritePaths)。
## 其他
- internal/plugin/proc:非法 JSON 帧的报错**可定位**(内容摘要 + 可能原因 +
修法)。生产实测 1038 条非法帧(插件往 stdout 打日志 = 污染协议通道)
- 示例插件 4 个 14 处 fmt.Printf → log.Printf
- hmapdev 模板同步修复;scaffold 判据剥离注释(模板注释里就含 fmt.Printf)
* chore: 收尾(主密钥轮换命令、IPC/知识库加固、SDK 对齐)
- cmd/homed-key-rotate:把 security 里的 RotateKey/RotateKeyFile/RekeySecrets
串成一条**可执行**的运维路径。没有它,E-1 就只是库里的能力而不是
"出事时能做的事",而轮换的价值恰恰在于能执行。
- cmd/homed:kmod_runtime(模块装配入口)、plugins_scheduled(failback
白名单)、memcandidate、bootstrap_order_test / shutdown_flush_test
- internal/ipc、internal/devicebridge、internal/knowledge:配套加固
- third_party/homeagent-sdk/sdk:PluginMgrAPI 增三态能力(mgrStop/mgrStart/
mgrIsRuntimeStopped)+ settings 对齐
判据:bootstrap_order_test(启动顺序不依赖手写序列)、
shutdown_flush_test(停机的两条路径必须对称 —— exit 42 会跳过 defer,
热更新路径下模块关闭/flush 曾全部丢失)。
* test(security): 测试夹具改用不可误认的占位值(修 push protection 拦截)
GitHub secret scanning 拦住了推送:三处测试夹具用了"看起来像真密钥"的
字面量:
internal/security/prefilter_test.go:39
internal/security/store_test.go:177
internal/security/survey_test.go:20
它们全是**假密钥**(`AKIAIOSFODNN7EXAMPLE` 是 AWS 官方文档的标准示例,
其余是 `abcdefghij...` 这类可读占位符),但扫描器无法区分 —— 它只看形态。
★ 不绕过(不用 unblock URL、不加 allowlist):直接改夹具。
原因:一旦允许"假密钥可以通过",真密钥混进来时就没有最后一道门了。
改法:保留**模式库匹配所需的结构**,把可识别内容换成 FAKE:
glpat-abcdefghijklmnopqrst → glpat-FAKE-TEST-TOKEN-NOT-REAL
sk-abcdefghij...012345 → sk-FAKE-TEST-KEY-NOT-REAL-0000000
AKIAIOSFODNN7EXAMPLE → AKIA0000FAKE0000TEST (保持 20 字符)
ASIAIOSFODNN7EXAMPLE → ASIA0000FAKE0000TEST
xoxb-123456789012-abcdefghijklmnop → xoxb-FAKE-TEST-TOKEN-NOT-REAL
★ 中途踩到一次:AWS 键的模式是 `\b(AKIA|ASIA)[0-9A-Z]{16}\b`(共 20 字符),
我第一次替换成 19 字符的 `AKIAFAKETESTKEY0000` ⇒ 模式匹配不上 ⇒
TestSurvey_WhatIsCaught / TestRecognizesCommonShapes /
TestPrefilterNeverBlocksRealMatches 三条当场变红。
判据正确地拒绝了"为了过扫描器而削弱覆盖"。
顺带核实:全仓 grep 无任何真实密钥泄漏。
* fix(packaging): package-linux.sh 的版本解析与 build.sh 统一
上一版只修了 build.sh,漏了 package-linux.sh —— 它仍只看 git describe:
VERSION="${VERSION:-$(git describe --tags --dirty)}"
无 tag 分支上 git describe 返回**分支名**
(backup/pre-identity-rewrite-20261005-56-g98850e1),守卫会正确拒绝,
但要求人**手动传 VERSION** 才能打包。而 build.sh 早已能自动回退 meta.Version
⇒ 同一个版本,走 build.sh 打得出来、走 package-linux.sh 打不出来。
危害不只是"要手动传参":运维为了跑通会去掉守卫,而分支名一旦进
meta.Version 就是**插件协议主版本**的来源 ⇒ 22 个子进程插件全部握手失败
(这是真实发生过的事故,见 3efa4e5)。
修法:两个脚本用同一套规则(git describe 仅在 vX.Y.Z 形态时采用,
否则回退 meta.Version),并对最终值做形态守卫。
判据:TestBothPackagingScriptsShareVersionRules —— 逐个读两个脚本,
要求都能从 meta/meta.go 取权威版本、都校验 git describe 形态。
变异(把 package-linux.sh 改回旧规则)咬住并准确指出是哪个脚本。
实测:不传 VERSION 跑 package-linux.sh,输出
[PKG] warn: git describe 给出非版本串(...),改用 meta.Version=1.4.0
Version: 1.4.0
* fix(test): 跨仓判据在 CI 上应 skip 而非 fail(修 PR 双红)
CI 上 "Go build / vet / test" 与 "Build linux/amd64" 双红:
--- FAIL: TestHmapdevTemplateImplementsAllPluginMgrMethods
bridge_sync_test.go:170: 读模板: open
../../../third_party/homeagent-sdk/tools/hmapdev/templates/proc_main.go.tmpl:
no such file or directory
## 根因:判据依赖了一个**被 gitignore 的路径**
`.gitignore:33` 有 `third_party/homeagent-sdk/tools/`(SDK 仓自治,本仓不跟踪)。
于是:
· 本机(完整 SDK 检出)有该文件 ⇒ 判据通过
· CI(只 checkout 本仓)没有该文件 ⇒ Fatalf ⇒ **必红**
我提交时只在本机跑测试、没看 CI,所以这个问题拖到 PR 才暴露。
## 修法
文件缺失时 `t.Skipf` 而不是 `t.Fatalf`。
★ 这不是"放弃检查":
· 跨仓一致性由 **SDK 仓自己的判据**守着
(tools/hmapdev/scaffold_stdout_test.go 等),那里才是模板的真实归属地
· 本判据在本机开发时**仍然生效**(已验证:有文件时 PASS,缺文件时 SKIP)
## 验证
· 本机(有文件) → PASS(判据真跑)
· 模拟 CI(移走 tools/)→ SKIP(不再 fail)
· 全量 53 包 ok / 0 fail
## 顺带
同目录还有 e2e_template_test.go 也读 tools/,但它是 `//go:build` 门控的
e2e 判据,CI 默认不跑,无需处理。
---------
Co-authored-by: JianFeeeee <JianFeeeee@users.noreply.gitcode.com>
This commit is contained in:
93
internal/config/backup_diag_test.go
Normal file
93
internal/config/backup_diag_test.go
Normal file
@ -0,0 +1,93 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/JianFeeeee/HomeAgent/internal/security"
|
||||
)
|
||||
|
||||
// ★★ E-2:备份来自**另一台机器**(密钥不同)时,审计必须报出“不可解”,
|
||||
// 而不是静默当明文/空值,也不是等到某个功能坏了才发现。
|
||||
//
|
||||
// 这是备份恢复场景的核心判据:db 能打开、表能读、但密文解不开 ——
|
||||
// 那种状态最容易被误判成“配置丢了”。
|
||||
func TestAuditSecretsDetectsForeignKeyBackup(t *testing.T) {
|
||||
// 本包的 codec 是**进程级全局**,测试必须还原现场,
|
||||
// 否则会把密钥泄漏给同包其它判据(实测:导致 GetInt 读到密文)。
|
||||
t.Cleanup(security.ClearConfigCodec)
|
||||
dir := t.TempDir()
|
||||
keyA := []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
|
||||
keyB := []byte("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
|
||||
|
||||
// 机器 A:写入一条加密配置
|
||||
security.ClearConfigCodec()
|
||||
if _, err := security.InitConfigCodec(keyA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
regA := NewConfigRegistry(filepath.Join(dir, "config.db"))
|
||||
regA.RegisterDef(cfgDef("core.llm.api_key"))
|
||||
if err := regA.Set("core.llm.api_key", "sk-machine-a"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ok, bad, err := regA.AuditSecrets()
|
||||
if err != nil || ok != 1 || bad != 0 {
|
||||
t.Fatalf("machine A 自审应为 ok=1 bad=0,实际 ok=%d bad=%d err=%v", ok, bad, err)
|
||||
}
|
||||
regA.Close()
|
||||
|
||||
// 机器 B:同一份 db,但密钥不同
|
||||
security.ClearConfigCodec()
|
||||
if _, err := security.InitConfigCodec(keyB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
regB := NewConfigRegistry(filepath.Join(dir, "config.db"))
|
||||
defer regB.Close()
|
||||
ok2, bad2, err := regB.AuditSecrets()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bad2 == 0 {
|
||||
t.Fatal("★ 外来密钥的备份未被识别 —— 会被误判为「配置丢了」而非「密钥不匹配」")
|
||||
}
|
||||
if ok2 != 0 {
|
||||
t.Errorf("外来密钥下可解条数应为 0,实际 %d", ok2)
|
||||
}
|
||||
// 读取该键必须**响亮报错**,不能把密文当明文交出去
|
||||
if v, err := regB.Get("core.llm.api_key"); err == nil {
|
||||
t.Fatalf("★ 密文解不开却返回了值: %v", v)
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 同一密钥下重启(正常恢复)必须全部可解 —— 不能把正常备份误报成坏。
|
||||
func TestAuditSecretsCleanOnSameKey(t *testing.T) {
|
||||
t.Cleanup(security.ClearConfigCodec)
|
||||
dir := t.TempDir()
|
||||
key := []byte("cccccccccccccccccccccccccccccccc")
|
||||
security.ClearConfigCodec()
|
||||
if _, err := security.InitConfigCodec(key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db := filepath.Join(dir, "config.db")
|
||||
reg := NewConfigRegistry(db)
|
||||
reg.RegisterDef(cfgDef("core.llm.api_key"))
|
||||
if err := reg.Set("core.llm.api_key", "sk-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Close()
|
||||
|
||||
if _, err := security.InitConfigCodec(key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg2 := NewConfigRegistry(db)
|
||||
defer reg2.Close()
|
||||
ok, bad, err := reg2.AuditSecrets()
|
||||
if err != nil || bad != 0 || ok != 1 {
|
||||
t.Fatalf("同密钥重启应为 ok=1 bad=0,实际 ok=%d bad=%d err=%v", ok, bad, err)
|
||||
}
|
||||
}
|
||||
|
||||
// cfgDef 造一个最小 secret 键定义。
|
||||
func cfgDef(key string) ConfigDef {
|
||||
return ConfigDef{Key: key, Type: "string", Secret: true}
|
||||
}
|
||||
@ -28,6 +28,16 @@ type ConfigDef struct {
|
||||
Options []string `json:"options,omitempty"`
|
||||
Hidden bool `json:"hidden,omitempty"`
|
||||
Category string `json:"category,omitempty"`
|
||||
|
||||
// Secret 标记该配置项为敏感值:**落盘加密且不回显**。
|
||||
//
|
||||
// ★ 与 Type=="password" 等价,但更显式。SDK 侧(pubsdk.ConfigDef)
|
||||
// 一直有这个字段,只是内核这边没实现 —— 插件早就声明了意图却没有效果。
|
||||
//
|
||||
// 两种写法都会生效(见 isSecretKey):
|
||||
// · Type: "password" 旧写法,兼容保留
|
||||
// · Secret: true 推荐,意图明确
|
||||
Secret bool `json:"secret,omitempty"`
|
||||
}
|
||||
|
||||
type ConfigRegistry struct {
|
||||
@ -36,6 +46,12 @@ type ConfigRegistry struct {
|
||||
dbPath string
|
||||
defs map[string]*ConfigDef
|
||||
llmSnapFile string
|
||||
|
||||
// secrets 是「需要加密落盘」的键集合(由 def 推导,见 isSecretKey)。
|
||||
//
|
||||
// 为何缓存成集合而不是每次查 def:写入是热路径,而 def 查询要拿锁;
|
||||
// 且 secret 判定必须对**无 def 的键**也能生效(见 secretByKeyPattern)。
|
||||
secrets map[string]bool
|
||||
}
|
||||
|
||||
func NewConfigRegistry(dbPath string) *ConfigRegistry {
|
||||
@ -47,7 +63,7 @@ func NewConfigRegistry(dbPath string) *ConfigRegistry {
|
||||
panic(fmt.Sprintf("open config db: %v", err))
|
||||
}
|
||||
db.Exec("PRAGMA journal_mode=WAL")
|
||||
r := &ConfigRegistry{db: db, dbPath: dbPath, defs: make(map[string]*ConfigDef)}
|
||||
r := &ConfigRegistry{db: db, dbPath: dbPath, defs: make(map[string]*ConfigDef), secrets: make(map[string]bool)}
|
||||
r.initCoreTable()
|
||||
return r
|
||||
}
|
||||
@ -133,11 +149,19 @@ func (r *ConfigRegistry) IsPluginDisabled(name string) bool {
|
||||
}
|
||||
|
||||
func (r *ConfigRegistry) ensurePluginTable(name string) {
|
||||
table := r.pluginTableName(name)
|
||||
r.db.Exec(fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)`, table))
|
||||
)`, r.pluginTableName(name)))
|
||||
}
|
||||
|
||||
// ensurePluginTableErr 同 ensurePluginTable 但返回错误(显式加密写入需要它)。
|
||||
func (r *ConfigRegistry) ensurePluginTableErr(name string) error {
|
||||
_, err := r.db.Exec(fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)`, r.pluginTableName(name)))
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *ConfigRegistry) pluginTableName(name string) string {
|
||||
@ -153,7 +177,11 @@ func (r *ConfigRegistry) pluginTableName(name string) string {
|
||||
func (r *ConfigRegistry) Register(key string, value interface{}) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.db.Exec(`INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)`, key, fmt.Sprint(value))
|
||||
stored := fmt.Sprint(value)
|
||||
if r.isSecretKey(key) {
|
||||
stored, _ = sealForStorage(key, stored)
|
||||
}
|
||||
r.db.Exec(`INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)`, key, stored)
|
||||
}
|
||||
|
||||
func (r *ConfigRegistry) RegisterDefault(key string, value interface{}) {
|
||||
@ -164,7 +192,12 @@ func (r *ConfigRegistry) RegisterDef(def ConfigDef) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.defs[def.Key] = &def
|
||||
r.db.Exec(`INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)`, def.Key, def.Default)
|
||||
// 默认值也要加密落盘(否则声明了 secret 的项一启动就是明文)。
|
||||
stored := def.Default
|
||||
if r.isSecretKey(def.Key) {
|
||||
stored, _ = sealForStorage(def.Key, stored)
|
||||
}
|
||||
r.db.Exec(`INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)`, def.Key, stored)
|
||||
}
|
||||
|
||||
func (r *ConfigRegistry) GetDef(key string) *ConfigDef {
|
||||
@ -306,7 +339,12 @@ func (r *ConfigRegistry) Get(key string) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return val, nil
|
||||
// 敏感项在库里是密文 ⇒ 对调用方透明解密(读接口语义不变)。
|
||||
if plain, oerr := openFromStorage(key, val); oerr == nil {
|
||||
return plain, nil
|
||||
} else {
|
||||
return nil, oerr
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ConfigRegistry) Set(key string, value interface{}) error {
|
||||
@ -315,7 +353,12 @@ func (r *ConfigRegistry) Set(key string, value interface{}) error {
|
||||
if strings.HasPrefix(key, "core.llm.") {
|
||||
r.writeLLMSnapshotLocked()
|
||||
}
|
||||
_, err := r.db.Exec(`INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)`, key, fmt.Sprint(value))
|
||||
stored := fmt.Sprint(value)
|
||||
// ★ 敏感项在**写库前**加密:库文件里只有密文。
|
||||
if r.isSecretKey(key) {
|
||||
stored, _ = sealForStorage(key, stored)
|
||||
}
|
||||
_, err := r.db.Exec(`INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)`, key, stored)
|
||||
if err == nil && strings.HasPrefix(key, "core.llm.sources.") {
|
||||
rest := strings.TrimPrefix(key, "core.llm.sources.")
|
||||
parts := strings.SplitN(rest, ".", 2)
|
||||
@ -455,6 +498,9 @@ func LoadLLMSnapshot(path string) (map[string]string, error) {
|
||||
}
|
||||
|
||||
// listPrefixLocked 调用方须持有锁;返回 prefix 开头的全部键值。
|
||||
//
|
||||
// ★ 返回的是**解密后**的值(调用方都是内核内部可信路径,如
|
||||
// ToConfig / LLM 快照 / guard 基线)。
|
||||
func (r *ConfigRegistry) listPrefixLocked(prefix string) map[string]string {
|
||||
out := make(map[string]string)
|
||||
rows, err := r.db.Query(`SELECT key, value FROM config WHERE key LIKE ? ORDER BY key`, prefix+"%")
|
||||
@ -465,7 +511,12 @@ func (r *ConfigRegistry) listPrefixLocked(prefix string) map[string]string {
|
||||
for rows.Next() {
|
||||
var k, v string
|
||||
if err := rows.Scan(&k, &v); err == nil {
|
||||
out[k] = v
|
||||
if plain, oerr := openFromStorage(k, v); oerr == nil {
|
||||
out[k] = plain
|
||||
} else {
|
||||
// 解不开就不给值:宁可缺失(可诊断)也不把密文当明文交出去。
|
||||
log.Printf("[config] listPrefix 解密 %s 失败,已跳过: %v", k, oerr)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
@ -483,7 +534,14 @@ func (r *ConfigRegistry) Dump() map[string]interface{} {
|
||||
for rows.Next() {
|
||||
var k, v string
|
||||
if err := rows.Scan(&k, &v); err == nil {
|
||||
result[k] = v
|
||||
// ★ 返回**明文**:Dump 的调用方都是内核内部可信路径
|
||||
//(ToConfig 重建 LLMSource、WebUI 设置页、插件读自身/他人配置)。
|
||||
// 本需求防的是「静态文件泄漏」,不是「内部读取」。
|
||||
if plain, oerr := openFromStorage(k, v); oerr == nil {
|
||||
result[k] = plain
|
||||
} else {
|
||||
log.Printf("[config] Dump 解密 %s 失败: %v", k, oerr)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
@ -723,7 +781,7 @@ func (r *ConfigRegistry) seedDBValues(dataDir string) {
|
||||
set("core.memory.documents", filepath.Join(dataDir, "memory", "documents"))
|
||||
// 发行版默认启用本地向量空间。用 chineseclip(text+image、512 维、实测
|
||||
// 稳态约 0.89GB、Apache-2.0)而不是 qwen3vl(视觉塔按需加载,峰值约 9.4GB):
|
||||
// 多数机器装不下后者。
|
||||
// 多数机器装不下后者。
|
||||
// 产物不在仓库里,用 scripts/export_chineseclip_onnx.py 生成到这个路径;
|
||||
// 产物缺失时 homed 会打印明确错误并退回 fastText 文本路径(不静默假装启用)。
|
||||
set("core.memory.multimodal_space.provider", "chineseclip")
|
||||
@ -885,7 +943,10 @@ func (r *ConfigRegistry) GetString(key, defaultVal string) string {
|
||||
if err != nil {
|
||||
return defaultVal
|
||||
}
|
||||
return v
|
||||
if plain, oerr := openFromStorage(key, v); oerr == nil {
|
||||
return plain
|
||||
}
|
||||
return defaultVal
|
||||
}
|
||||
|
||||
func (r *ConfigRegistry) GetInt(key string, defaultVal int) int {
|
||||
@ -1154,7 +1215,11 @@ func (r *ConfigRegistry) SetPluginConfig(name, key string, value interface{}) er
|
||||
defer r.mu.Unlock()
|
||||
r.ensurePluginTable(name)
|
||||
table := r.pluginTableName(name)
|
||||
_, err := r.db.Exec(fmt.Sprintf(`INSERT OR REPLACE INTO %s (key, value) VALUES (?, ?)`, table), key, fmt.Sprint(value))
|
||||
stored := fmt.Sprint(value)
|
||||
if r.isSecretKey("plugin." + name + "." + key) {
|
||||
stored, _ = sealForStorage("plugin."+name+"."+key, stored)
|
||||
}
|
||||
_, err := r.db.Exec(fmt.Sprintf(`INSERT OR REPLACE INTO %s (key, value) VALUES (?, ?)`, table), key, stored)
|
||||
return err
|
||||
}
|
||||
|
||||
@ -1183,17 +1248,65 @@ func (p *PluginSettings) Get(key string) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return val, nil
|
||||
// 敏感项透明解密
|
||||
if plain, oerr := openFromStorage("plugin."+p.name+"."+key, val); oerr == nil {
|
||||
return plain, nil
|
||||
} else {
|
||||
return nil, oerr
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PluginSettings) Set(key string, value interface{}) error {
|
||||
p.registry.mu.Lock()
|
||||
defer p.registry.mu.Unlock()
|
||||
_, err := p.registry.db.Exec(fmt.Sprintf(`INSERT OR REPLACE INTO %s (key, value) VALUES (?, ?)`, p.table), key, fmt.Sprint(value))
|
||||
stored := fmt.Sprint(value)
|
||||
// ★ 插件敏感项同样加密落盘(插件无感知:它 Set 明文,Get 也得到明文)。
|
||||
if p.isSecretKeyLocal(key) {
|
||||
stored, _ = sealForStorage("plugin."+p.name+"."+key, stored)
|
||||
}
|
||||
_, err := p.registry.db.Exec(fmt.Sprintf(`INSERT OR REPLACE INTO %s (key, value) VALUES (?, ?)`, p.table), key, stored)
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove 删除插件配置中的单个键(用于插件删除时的自身配置清理)。
|
||||
// SetSecret 强制加密写入(不看键名,也不需 def)。
|
||||
//
|
||||
// ★ 为何要显式 API:键名模式无法覆盖所有情形 —— 插件可能用
|
||||
// `blob`、`payload`、`conn` 这类中性键名存凭据。显式声明意图比猜名字可靠。
|
||||
//
|
||||
// 未装配密钥时 **拒绝写入**(不静默存明文):插件以为存了密文而
|
||||
// 实际是明文,是最危险的静默降级。空值例外(删除语义)。
|
||||
func (p *PluginSettings) SetSecret(key string, value interface{}) error {
|
||||
stored := fmt.Sprint(value)
|
||||
sealed := stored
|
||||
if stored != "" {
|
||||
var ok bool
|
||||
sealed, ok = sealForStorage("plugin."+p.name+"."+key, stored)
|
||||
if !ok {
|
||||
return fmt.Errorf("config: 密钥未装配,拒绝以明文存储敏感项 %q", key)
|
||||
}
|
||||
}
|
||||
p.registry.mu.Lock()
|
||||
defer p.registry.mu.Unlock()
|
||||
if err := p.registry.ensurePluginTableErr(p.name); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := p.registry.db.Exec(
|
||||
fmt.Sprintf(`INSERT OR REPLACE INTO %s (key, value) VALUES (?, ?)`, p.table), key, sealed)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetSecret 读取由 SetSecret 写入的值(透明解密)。
|
||||
func (p *PluginSettings) GetSecret(key string) (string, error) {
|
||||
p.registry.mu.RLock()
|
||||
defer p.registry.mu.RUnlock()
|
||||
var val string
|
||||
err := p.registry.db.QueryRow(
|
||||
fmt.Sprintf(`SELECT value FROM %s WHERE key = ?`, p.table), key).Scan(&val)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return openFromStorage("plugin."+p.name+"."+key, val)
|
||||
}
|
||||
func (p *PluginSettings) Remove(key string) error {
|
||||
p.registry.mu.Lock()
|
||||
defer p.registry.mu.Unlock()
|
||||
@ -1226,10 +1339,18 @@ func (p *PluginSettings) RegisterDef(def ConfigDef) {
|
||||
// 只有注册配置定义才创建插件配置表:任意 scope 的读写不得隐式建表,
|
||||
// 避免非插件(如 SKILL 目录名)被注册成配置命名空间。
|
||||
p.registry.ensurePluginTable(p.name)
|
||||
p.registry.db.Exec(fmt.Sprintf(`INSERT OR IGNORE INTO %s (key, value) VALUES (?, ?)`, p.table), def.Key, def.Default)
|
||||
qualified := "plugin." + p.name + "." + def.Key
|
||||
|
||||
localKey := def.Key // 表内用局部键
|
||||
qualified := "plugin." + p.name + "." + localKey // defs 里用限定键
|
||||
def.Key = qualified
|
||||
p.registry.defs[def.Key] = &def
|
||||
// ★ def 必须先入 defs:isSecretKey 靠它判定,而下面的默认值要加密。
|
||||
p.registry.defs[qualified] = &def
|
||||
|
||||
stored := def.Default
|
||||
if p.registry.isSecretKey(qualified) {
|
||||
stored, _ = sealForStorage(qualified, stored)
|
||||
}
|
||||
p.registry.db.Exec(fmt.Sprintf(`INSERT OR IGNORE INTO %s (key, value) VALUES (?, ?)`, p.table), localKey, stored)
|
||||
}
|
||||
|
||||
func (p *PluginSettings) ListDefs(prefix string) []*ConfigDef {
|
||||
|
||||
408
internal/config/secret.go
Normal file
408
internal/config/secret.go
Normal file
@ -0,0 +1,408 @@
|
||||
package config
|
||||
|
||||
// 配置落盘加密(敏感项 at-rest encryption)。
|
||||
//
|
||||
// ## 要解决的问题
|
||||
//
|
||||
// `config.db` 是 **0644 全局可读**的(它同目录还有 WAL/SHM),
|
||||
// 而里面装着 LLM API 密钥、WebUI 口令、插件凭据等 —— 任何本机用户
|
||||
// `sqlite3 config.db 'select * from config'` 就能拿到全部明文。
|
||||
//
|
||||
// ## 做法:在**存储边界**加密,读写接口不变
|
||||
//
|
||||
// Set/Register/seed → Seal → DB 里是 `enc:v1:<base64>`
|
||||
// Get/Dump/ToConfig → Open → 调用方永远只看到明文
|
||||
//
|
||||
// ★ 关键取舍:**读接口保持"返回明文"**。
|
||||
//
|
||||
// 初稿曾考虑让 `Dump()` 返回掩码、让 WebUI 看不到明文。但那样会同时
|
||||
// 打断 `ToConfig()`(它靠 Dump 重建 LLMSource,含 api_key)与任何
|
||||
// 需要真实值的内部读取方 —— 而它们**本来就在可信边界内**。
|
||||
// 本需求要防的是「静态文件泄漏」,不是「内部读取」。
|
||||
//
|
||||
// ## 标记来源(两种都支持)
|
||||
//
|
||||
// 1. `ConfigDef.Secret == true` ← SDK 里早就有这个字段,但从未被实现
|
||||
// 2. `ConfigDef.Type == "password"` / `"secret"`
|
||||
//
|
||||
// ## 无 def 的键怎么办
|
||||
//
|
||||
// 插件的 key 常常没有 def(`Set()` 可以直接写任意键)。
|
||||
// 所以还要靠**键名模式**兜底(`secretKeyPattern`),否则
|
||||
// `plugin.qq.token` 这类会被漏掉。
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/JianFeeeee/HomeAgent/internal/security"
|
||||
)
|
||||
|
||||
// secretSegmentPattern 是无 def 时的兜底判定。
|
||||
//
|
||||
// ## 为何不能直接 `strings.Contains(key, "token")`
|
||||
//
|
||||
// 初版就是这么写的,结果把这两个**非敏感**项也加密了:
|
||||
//
|
||||
// core.llm.max_tokens ← 输出 token 上限
|
||||
// core.agent.context.max_target_tokens ← 上下文预算
|
||||
//
|
||||
// 功能上无害(透明解密,仍可用),但语义错了,且库变得难以人工检查。
|
||||
// 根因:`max_tokens` 包含子串 "token",而它是**复数、指数量**。
|
||||
//
|
||||
// ## 现在的判据:按**词段**匹配
|
||||
//
|
||||
// 先把键按 `.` `_` `-` 切成词段,再看:
|
||||
//
|
||||
// 词段完全等于敏感词 → 命中(token / password / apikey …)
|
||||
// 词段以 `_<敏感词>` 结尾 → 命中(api_key / access_token …)
|
||||
//
|
||||
// 关键差别:`max_tokens` 的末词段是 `tokens`(复数),不等于 `token`,
|
||||
// 也不以 `_token` 结尾 ⇒ **不命中**。而 `api_key` 末词段是 `key`
|
||||
// 且整串以 `_key` 结尾 ⇒ 命中。
|
||||
var secretWords = []string{
|
||||
"token", "password", "passwd", "secret", "credential", "credentials",
|
||||
"apikey", "key",
|
||||
}
|
||||
|
||||
// secretExactSegments 是允许“整词即敏感”的情形。
|
||||
//
|
||||
// `key` 单独成词段(如某插件的配置就叫 `key`)算敏感;但像 `keyboard`、
|
||||
// `keys`(复数)这样的就不算。
|
||||
func looksLikeSecretKey(key string) bool {
|
||||
lower := strings.ToLower(key)
|
||||
// 切成词段:先按命名空间分隔,再拆下划线/连字符
|
||||
for _, part := range strings.FieldsFunc(lower, func(r rune) bool {
|
||||
return r == '.' || r == '_' || r == '-'
|
||||
}) {
|
||||
for _, w := range secretWords {
|
||||
if part == w {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
// 复合形态:整串以 _<敏感词> 结尾(api_key / access_token / client_secret)
|
||||
for _, w := range secretWords {
|
||||
if strings.HasSuffix(lower, "_"+w) || strings.HasSuffix(lower, "-"+w) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isSecretKey 判定一个(全局或插件内局部的)键是否敏感。
|
||||
//
|
||||
// 判定顺序:显式 def(最权威) → 键名模式(兜底)。
|
||||
func (r *ConfigRegistry) isSecretKey(key string) bool {
|
||||
// 调用方须持锁(读或写皆可)
|
||||
if d, ok := r.defs[key]; ok {
|
||||
if d.Secret || d.Type == "password" || d.Type == "secret" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return looksLikeSecretKey(key)
|
||||
}
|
||||
|
||||
// isSecretKeyLocal 供 PluginSettings 用(键是插件内局部键,无命名空间前缀)。
|
||||
func (p *PluginSettings) isSecretKeyLocal(key string) bool {
|
||||
return p.registry.isSecretKey("plugin." + p.name + "." + key)
|
||||
}
|
||||
|
||||
// sealForStorage 在写库前加密(仅对敏感键 + 编解码器已装配时)。
|
||||
//
|
||||
// 返回值语义:加密发生则 mem=false(调用方据此决定是否需回读校验);
|
||||
// 非敏感键或未装配 codec 时原样返回。
|
||||
func sealForStorage(key, value string) (string, bool) {
|
||||
if !security.IsEncrypted(value) {
|
||||
c := security.ConfigCodec()
|
||||
if c == nil || !c.Enabled() {
|
||||
return value, false
|
||||
}
|
||||
if sealed, err := c.Seal(value); err == nil {
|
||||
return sealed, true
|
||||
} else {
|
||||
log.Printf("[config] 加密 %s 失败(将按明文写入,此项暴露风险): %v", key, err)
|
||||
}
|
||||
}
|
||||
return value, false
|
||||
}
|
||||
|
||||
// openFromStorage 在读库后解密。
|
||||
//
|
||||
// 非密文原样返回(**存量明文兼容**):老数据不需要一次性迁移。
|
||||
// 密文但解不开 ⇒ **响亮失败**(返回错误而非密文),因为把密文
|
||||
// 当明文交出去会让下游拿到垃圾(比如把 `enc:v1:...` 当 API key 发出去)。
|
||||
func openFromStorage(key, stored string) (string, error) {
|
||||
if !security.IsEncrypted(stored) {
|
||||
return stored, nil
|
||||
}
|
||||
c := security.ConfigCodec()
|
||||
if c == nil || !c.Enabled() {
|
||||
return "", security.ErrNoMasterKey
|
||||
}
|
||||
plain, err := c.Open(stored)
|
||||
if err != nil {
|
||||
log.Printf("[config] 解密 %s 失败: %v", key, err)
|
||||
return "", err
|
||||
}
|
||||
return plain, nil
|
||||
}
|
||||
|
||||
// EncryptExistingSecrets 把库里**尚为明文**的敏感项就地加密(启动时跑一次)。
|
||||
//
|
||||
// ## 为何需要
|
||||
//
|
||||
// 加密只对新写入生效。升级前库里已有的 api_key / 口令仍是明文 ——
|
||||
// 不迁移的话"升级了但密钥还在裸奔",而且用户无法察觉。
|
||||
//
|
||||
// ## 可回滚
|
||||
//
|
||||
// 只改值形态、不改键名与表结构,旧版本二进制读明文项仍然工作
|
||||
// (它不认 `enc:v1:` 前缀,会把密文当明文用 —— 那是**功能坏但可见**的
|
||||
// 失败,不是静默错值)。所以升级要么配套换二进制,要么备份。
|
||||
//
|
||||
// 返回 (加密条数, 错误)。幂等:已加密的项不会被二次加密。
|
||||
func (r *ConfigRegistry) EncryptExistingSecrets() (int, error) {
|
||||
c := security.ConfigCodec()
|
||||
if c == nil || !c.Enabled() {
|
||||
return 0, security.ErrNoMasterKey
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
type row struct{ table, key, val string }
|
||||
var todo []row
|
||||
|
||||
// ① 全局 config 表
|
||||
rows, err := r.db.Query(`SELECT key, value FROM config`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var k, v string
|
||||
if err := rows.Scan(&k, &v); err != nil {
|
||||
continue
|
||||
}
|
||||
if !r.isSecretKey(k) || security.IsEncrypted(v) || v == "" {
|
||||
continue
|
||||
}
|
||||
todo = append(todo, row{"config", k, v})
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
// ② 各插件表
|
||||
for _, name := range r.ListPluginsLocked() {
|
||||
table := r.pluginTableName(name)
|
||||
pr, err := r.db.Query("SELECT key, value FROM " + table)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for pr.Next() {
|
||||
var k, v string
|
||||
if err := pr.Scan(&k, &v); err != nil {
|
||||
continue
|
||||
}
|
||||
if !r.isSecretKey("plugin."+name+"."+k) || security.IsEncrypted(v) || v == "" {
|
||||
continue
|
||||
}
|
||||
todo = append(todo, row{table, k, v})
|
||||
}
|
||||
pr.Close()
|
||||
}
|
||||
|
||||
n := 0
|
||||
for _, t := range todo {
|
||||
sealed, err := c.Seal(t.val)
|
||||
if err != nil {
|
||||
log.Printf("[config] 迁移加密 %s.%s 失败: %v", t.table, t.key, err)
|
||||
continue
|
||||
}
|
||||
if _, err := r.db.Exec(
|
||||
"UPDATE "+t.table+" SET value = ? WHERE key = ?", sealed, t.key); err != nil {
|
||||
log.Printf("[config] 迁移加密 %s.%s 写回失败: %v", t.table, t.key, err)
|
||||
continue
|
||||
}
|
||||
n++
|
||||
}
|
||||
if n > 0 {
|
||||
log.Printf("[config] 已加密 %d 条存量敏感配置(落盘不再有明文)", n)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// RekeySecrets 把库里的密文重加密到**当前**主密钥(E-1 密钥轮换后的收口)。
|
||||
//
|
||||
// 与 EncryptExistingSecrets 的区别:
|
||||
// - 后者处理「明文 → 密文」(升级路径);
|
||||
// - 本函数处理「旧钥密文 → 新钥密文」(轮换路径)。
|
||||
//
|
||||
// 为何必须有:轮换只换密钥文件 / keyring 是不够的 —— 旧密文仍由旧钥保护,
|
||||
// 而旧钥必须留在环里才能读它们。不重加密的话,旧钥永远不会退出。
|
||||
//
|
||||
// 幂等:已是当前钥的项不动。解不开的项**响亮计数**并跳过(不静默删)。
|
||||
func (r *ConfigRegistry) RekeySecrets() (int, int, error) {
|
||||
c := security.ConfigCodec()
|
||||
if c == nil || !c.Enabled() {
|
||||
return 0, 0, security.ErrNoMasterKey
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
tables := []string{"config"}
|
||||
for _, name := range r.ListPluginsLocked() {
|
||||
tables = append(tables, r.pluginTableName(name))
|
||||
}
|
||||
|
||||
rekeyed, failed := 0, 0
|
||||
for _, table := range tables {
|
||||
rows, err := r.db.Query("SELECT key, value FROM " + table)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
type pair struct{ k, v string }
|
||||
var need []pair
|
||||
for rows.Next() {
|
||||
var k, v string
|
||||
if err := rows.Scan(&k, &v); err != nil {
|
||||
continue
|
||||
}
|
||||
if c.NeedsRekey(v) {
|
||||
need = append(need, pair{k, v})
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
for _, p := range need {
|
||||
fresh, err := c.Rekey(p.v)
|
||||
if err != nil {
|
||||
// ★ 解不开不能静默跳:那是“密钥环缺一代”的信号,必须可见。
|
||||
failed++
|
||||
log.Printf("[config] 重加密 %s.%s 失败(旧密钥不在环里?): %v", table, p.k, err)
|
||||
continue
|
||||
}
|
||||
if _, err := r.db.Exec("UPDATE "+table+" SET value = ? WHERE key = ?", fresh, p.k); err != nil {
|
||||
failed++
|
||||
log.Printf("[config] 重加密 %s.%s 写回失败: %v", table, p.k, err)
|
||||
continue
|
||||
}
|
||||
rekeyed++
|
||||
}
|
||||
}
|
||||
if rekeyed > 0 || failed > 0 {
|
||||
log.Printf("[config] 密钥轮换重加密:完成 %d 条,失败 %d 条", rekeyed, failed)
|
||||
}
|
||||
return rekeyed, failed, nil
|
||||
}
|
||||
|
||||
// AuditSecrets 统计库里密文的可读性(E-2:备份跨机器恢复的诊断)。
|
||||
//
|
||||
// 为何需要:备份恢复到另一台机器时,DB 里的密文是**旧机器的密钥**加的。
|
||||
// 此前只有读某一条具体配置时才会报错,用户看到的是「某个功能坏了」,
|
||||
// 而不是「这份备份与当前密钥不匹配」。这个审计把事实一次性说清楚。
|
||||
//
|
||||
// 返回 (可解, 不可解)。不可解 > 0 就是密钥不匹配/缺代的硬信号。
|
||||
func (r *ConfigRegistry) AuditSecrets() (int, int, error) {
|
||||
c := security.ConfigCodec()
|
||||
if c == nil || !c.Enabled() {
|
||||
return 0, 0, security.ErrNoMasterKey
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
tables := []string{"config"}
|
||||
for _, name := range r.ListPluginsLocked() {
|
||||
tables = append(tables, r.pluginTableName(name))
|
||||
}
|
||||
ok, bad := 0, 0
|
||||
for _, table := range tables {
|
||||
rows, err := r.db.Query("SELECT value FROM " + table)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for rows.Next() {
|
||||
var v string
|
||||
if err := rows.Scan(&v); err != nil {
|
||||
continue
|
||||
}
|
||||
if !security.IsEncrypted(v) {
|
||||
continue // 明文(未加密项)不计入
|
||||
}
|
||||
if _, err := c.Open(v); err == nil {
|
||||
ok++
|
||||
} else {
|
||||
bad++
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
}
|
||||
return ok, bad, nil
|
||||
}
|
||||
|
||||
// ListPluginsLocked 是 ListPlugins 的不加锁版本(调用方已持锁)。
|
||||
func (r *ConfigRegistry) ListPluginsLocked() []string {
|
||||
rows, err := r.db.Query(
|
||||
`SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'config_%' ORDER BY name`)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var t string
|
||||
if err := rows.Scan(&t); err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, strings.TrimPrefix(t, "config_"))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// IsSecret 报告某个(全局或 plugin. 前缀的)键是否敏感。
|
||||
//
|
||||
// 用途(E-3):WebUI 在返回设置时必须用它**屏蔽明文**,否则任何能打开
|
||||
// 设置页的人都看得到全部密钥(含其他插件的)。
|
||||
//
|
||||
// 它刻意复用与落盘加密**同一套判定**(isSecretKey):两处判定若不一致,
|
||||
// 就会出现「已加密但界面照旧显示明文」或反向的漏洞。
|
||||
func (r *ConfigRegistry) IsSecret(key string) bool {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
return r.isSecretKey(key)
|
||||
}
|
||||
|
||||
// SecretKeys 返回当前被判定为敏感的键(供诊断 / 测试 / WebUI 标记)。
|
||||
func (r *ConfigRegistry) SecretKeys() []string {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
var out []string
|
||||
seen := map[string]bool{}
|
||||
for k := range r.defs {
|
||||
if r.isSecretKey(k) && !seen[k] {
|
||||
seen[k] = true
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DB 暴露底层连接(仅供**同仓测试**读取原始密文用)。
|
||||
//
|
||||
// 语义警告:它绕过全部加解密与权限逻辑,仅用于判据里断言
|
||||
// 「磁盘上确实是密文」。生产代码不得使用。
|
||||
func (r *ConfigRegistry) DB() *sql.DB { return r.db }
|
||||
|
||||
// ResetTestCodec 为判据装配一把固定主密钥。
|
||||
//
|
||||
// 单独放在非 _test 文件里,是因为 proc 包(另一个包)的端到端判据
|
||||
// 也需要它 —— 跨包无法直接调 *_test.go 里的辅助函数。
|
||||
func ResetTestCodec(t interface {
|
||||
Helper()
|
||||
Fatalf(string, ...interface{})
|
||||
}) {
|
||||
if _, err := security.InitConfigCodec(
|
||||
[]byte("0123456789abcdef0123456789abcdef")); err != nil {
|
||||
t.Fatalf("装配测试 codec 失败: %v", err)
|
||||
}
|
||||
}
|
||||
416
internal/config/secret_test.go
Normal file
416
internal/config/secret_test.go
Normal file
@ -0,0 +1,416 @@
|
||||
package config
|
||||
|
||||
// 配置落盘加密的判据。
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/JianFeeeee/HomeAgent/internal/security"
|
||||
)
|
||||
|
||||
func testCodec(t *testing.T) {
|
||||
t.Helper()
|
||||
if _, err := security.InitConfigCodec([]byte("0123456789abcdef0123456789abcdef")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func newSecReg(t *testing.T) *ConfigRegistry {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
testCodec(t)
|
||||
return NewConfigRegistry(filepath.Join(dir, "config.db"))
|
||||
}
|
||||
|
||||
// 直接在 sqlite 层面读原始值(绕过 ConfigRegistry 的解密)。
|
||||
func rawValue(t *testing.T, r *ConfigRegistry, key string) string {
|
||||
t.Helper()
|
||||
var v string
|
||||
if err := r.db.QueryRow(`SELECT value FROM config WHERE key = ?`, key).Scan(&v); err != nil {
|
||||
t.Fatalf("读原始值失败: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// ★★ 判据:敏感配置**落盘是密文**,而读接口返回明文。
|
||||
func TestSecretEncryptedOnDiskPlainOnRead(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
const secret = "sk-super-secret-value-1234567890"
|
||||
|
||||
if err := r.Set("core.llm.api_key", secret); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// ① 磁盘上是密文
|
||||
raw := rawValue(t, r, "core.llm.api_key")
|
||||
if raw == secret {
|
||||
t.Fatal("敏感项在磁盘上是明文")
|
||||
}
|
||||
if !security.IsEncrypted(raw) {
|
||||
t.Fatalf("应有 enc:v1: 前缀,实际 %q", raw)
|
||||
}
|
||||
|
||||
// ② 读接口返回明文(内部可信路径语义不变)
|
||||
got, err := r.Get("core.llm.api_key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != secret {
|
||||
t.Fatalf("Get 应返回明文,实际 %v", got)
|
||||
}
|
||||
// ③ GetString / Dump 同样给明文
|
||||
if r.GetString("core.llm.api_key", "") != secret {
|
||||
t.Error("GetString 应返回明文")
|
||||
}
|
||||
if r.Dump()["core.llm.api_key"] != secret {
|
||||
t.Error("Dump 应返回明文(ToConfig 依赖它)")
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 判据:**非敏感项不受影响**(不能被误加密)。
|
||||
func TestNonSecretStaysPlain(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
if err := r.Set("core.llm.base_url", "https://api.deepseek.com"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := rawValue(t, r, "core.llm.base_url")
|
||||
if raw != "https://api.deepseek.com" {
|
||||
t.Fatalf("非敏感项不应被加密: %q", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 判据:`Secret: true` 与 `Type: "password"` 两种声明都生效。
|
||||
func TestBothDeclarationFormsWork(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
r.RegisterDef(ConfigDef{Key: "core.a.token_field", Default: "", Secret: true})
|
||||
r.RegisterDef(ConfigDef{Key: "core.b.password_field", Default: "", Type: "password"})
|
||||
|
||||
for _, k := range []string{"core.a.token_field", "core.b.password_field"} {
|
||||
if err := r.Set(k, "value-1234567890"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !security.IsEncrypted(rawValue(t, r, k)) {
|
||||
t.Errorf("%s 未被加密(Secret 或 password 声明未生效)", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 判据:**插件配置同样加密**(插件无感知)。
|
||||
func TestPluginSecretEncrypted(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
ps := r.PluginConfig("demo")
|
||||
ps.RegisterDef(ConfigDef{Key: "token", Default: "", Secret: true})
|
||||
|
||||
const secret = "plugin-token-abcdef123456"
|
||||
if err := ps.Set("token", secret); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 磁盘(插件表)上是密文
|
||||
var raw string
|
||||
if err := r.db.QueryRow(`SELECT value FROM config_demo WHERE key = 'token'`).Scan(&raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !security.IsEncrypted(raw) {
|
||||
t.Fatalf("插件敏感项应加密,实际 %q", raw)
|
||||
}
|
||||
// 插件读回明文
|
||||
got, err := ps.Get("token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != secret {
|
||||
t.Fatalf("插件应读回明文,实际 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 判据:无 def 的插件键靠**键名模式**兜底加密。
|
||||
func TestPluginSecretByKeyPattern(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
ps := r.PluginConfig("demo2")
|
||||
// 先注册一个**非敏感** def:插件表只在 RegisterDef 时创建,
|
||||
// 但 api_key 这个键本身没有 def —— 正好检验键名模式兜底。
|
||||
ps.RegisterDef(ConfigDef{Key: "enabled", Default: "true"})
|
||||
if err := ps.Set("api_key", "abcdefgh12345678"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var raw string
|
||||
r.db.QueryRow(`SELECT value FROM config_demo2 WHERE key = 'api_key'`).Scan(&raw)
|
||||
if !security.IsEncrypted(raw) {
|
||||
t.Fatalf("无 def 时 api_key 键名应触发加密,实际 %q", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 判据:存量明文在启动迁移后被加密(幂等)。
|
||||
func TestMigrateExistingSecrets(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
// 模拟升级前的明文存量(直接写库,绕过 Set)
|
||||
r.db.Exec(`INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)`,
|
||||
"core.llm.api_key", "legacy-plaintext-key-123")
|
||||
r.db.Exec(`INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)`,
|
||||
"webui.listen_addr", ":8080")
|
||||
|
||||
n, err := r.EncryptExistingSecrets()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Fatalf("应加密 1 条,实际 %d", n)
|
||||
}
|
||||
if !security.IsEncrypted(rawValue(t, r, "core.llm.api_key")) {
|
||||
t.Error("存量敏感项未被加密")
|
||||
}
|
||||
// 非敏感项不动
|
||||
if rawValue(t, r, "webui.listen_addr") != ":8080" {
|
||||
t.Error("非敏感项被误改")
|
||||
}
|
||||
// 迁移后仍可读明文
|
||||
if v, _ := r.Get("core.llm.api_key"); v != "legacy-plaintext-key-123" {
|
||||
t.Errorf("迁移后应可读明文,实际 %v", v)
|
||||
}
|
||||
// 幂等
|
||||
if n2, _ := r.EncryptExistingSecrets(); n2 != 0 {
|
||||
t.Errorf("迁移应幂等,第二次却加密了 %d 条", n2)
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 判据:**存量明文不需要迁移也能读**(老数据向后兼容)。
|
||||
func TestLegacyPlaintextReadableWithoutMigration(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
r.db.Exec(`INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)`,
|
||||
"core.llm.api_key", "still-plain")
|
||||
v, err := r.Get("core.llm.api_key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v != "still-plain" {
|
||||
t.Fatalf("明文存量应可读,实际 %v", v)
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 判据:换密钥后**响亮失败**(不静默返回密文)。
|
||||
func TestWrongKeyFailsLoudly(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
if err := r.Set("core.llm.api_key", "secret-value-1234567890"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 换一把主密钥
|
||||
if _, err := security.InitConfigCodec([]byte("ffffffffffffffffffffffffffffffff")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.Get("core.llm.api_key"); err == nil {
|
||||
t.Fatal("换密钥后必须报错,不能把密文当明文返回")
|
||||
}
|
||||
// Dump 也不得吐密文
|
||||
if v := r.Dump()["core.llm.api_key"]; v != nil {
|
||||
if s, ok := v.(string); ok && strings.HasPrefix(s, "enc:") {
|
||||
t.Fatal("Dump 把密文交出去了")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 判据:未装配 codec 时退化为明文读写(本地开发/测试不阻塞)。
|
||||
func TestNoCodecDegradesToPlain(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
// 清空全局 codec
|
||||
security.ClearConfigCodec()
|
||||
r := NewConfigRegistry(filepath.Join(dir, "c.db"))
|
||||
if err := r.Set("core.llm.api_key", "plain-dev"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rawValue(t, r, "core.llm.api_key") != "plain-dev" {
|
||||
t.Error("未装配 codec 时应保持明文")
|
||||
}
|
||||
_ = os.Remove
|
||||
}
|
||||
|
||||
// ★ 判据:域隔离 —— 配置子密钥与别名密钥不可互换。
|
||||
func TestDomainSeparation(t *testing.T) {
|
||||
master := []byte("0123456789abcdef0123456789abcdef")
|
||||
cfgCodec, err := security.NewCodec(master, "config-at-rest")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
otherCodec, err := security.NewCodec(master, "some-other-domain")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sealed, err := cfgCodec.Seal("hello")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := otherCodec.Open(sealed); err == nil {
|
||||
t.Fatal("不同域的子密钥不应能解开 —— 域隔离失效")
|
||||
}
|
||||
if got, _ := cfgCodec.Open(sealed); got != "hello" {
|
||||
t.Fatal("同域应可解")
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 判据:**ToConfig 在加密开启后仍能取到真 api_key**。
|
||||
//
|
||||
// 这是最容易被加密改坏的一条:ToConfig 靠 Dump() 重建 LLMSource。
|
||||
// 若 Dump 改返回掩码/密文,LLM 就会拿着垃圾去调上游 —— 而且
|
||||
// 失败现象是「认证失败」,与配置加密毫无关联,归因极难。
|
||||
func TestToConfigStillGetsRealAPIKey(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
const key = "sk-real-key-for-upstream-123456"
|
||||
if err := r.Set("core.llm.api_key", key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Set("core.llm.sources.probe.base_url", "https://example.com"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Set("core.llm.sources.probe.api_key", key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Set("core.llm.sources.probe.model", "m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg := r.ToConfig()
|
||||
if cfg.LLM.APIKey != key {
|
||||
t.Fatalf("ToConfig 的 APIKey 不真:%q", cfg.LLM.APIKey)
|
||||
}
|
||||
var found bool
|
||||
for _, s := range cfg.LLM.Sources {
|
||||
if s.Name == "probe" {
|
||||
found = true
|
||||
if s.APIKey != key {
|
||||
t.Fatalf("source api_key 不真:%q", s.APIKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("source probe 丢失")
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 判据:**数量类键名不得被误判为敏感**。
|
||||
//
|
||||
// 这是真机跑出来的缺陷:初版用 strings.Contains(key,"token"),
|
||||
// 把 core.llm.max_tokens(输出上限)与
|
||||
// core.agent.context.max_target_tokens(上下文预算)也加密了。
|
||||
// 功能上无害,但语义错误、且库变得无法人工检查。
|
||||
func TestNonSecretTokenCountsNotEncrypted(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
benign := []string{
|
||||
"core.llm.max_tokens",
|
||||
"core.agent.context.max_target_tokens",
|
||||
"core.compact.target_tokens",
|
||||
"core.keyboard_layout", // 含 "key" 但不是凭据
|
||||
"core.monkey_mode", // 同上
|
||||
"webui.listen_addr",
|
||||
"core.llm.temperature",
|
||||
}
|
||||
for _, k := range benign {
|
||||
if r.isSecretKey(k) {
|
||||
t.Errorf("%q 被误判为敏感(会被无谓加密)", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 判据:真敏感键名必须命中(含无 def 的插件键)。
|
||||
func TestSecretKeyNamesDetected(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
sensitive := []string{
|
||||
"core.llm.api_key",
|
||||
"core.llm.sources.x.access_token",
|
||||
"plugin.qq.token",
|
||||
"plugin.demo.password",
|
||||
"plugin.a.client_secret",
|
||||
"plugin.b.apikey",
|
||||
"plugin.c.key",
|
||||
"core.memory.multimodal_space.options.api_key",
|
||||
}
|
||||
for _, k := range sensitive {
|
||||
if !r.isSecretKey(k) {
|
||||
t.Errorf("%q 应被判定为敏感", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 判据:显式加密 API(SetSecret/GetSecret)**不看键名**也加密。
|
||||
//
|
||||
// 存在意义:插件可能用中性键名(blob/payload/conn)存凭据,
|
||||
// 键名模式猜不到 ⇒ 必须能显式声明意图。
|
||||
func TestExplicitSetSecretIgnoresKeyName(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
ps := r.PluginConfig("demo3")
|
||||
ps.RegisterDef(ConfigDef{Key: "enabled", Default: "1"})
|
||||
|
||||
const neutral = "blob" // 中性键名,模式判定为**非敏感**
|
||||
if r.isSecretKey("plugin.demo3." + neutral) {
|
||||
t.Fatal("前提失效:blob 不该被模式判定为敏感")
|
||||
}
|
||||
|
||||
const secret = "creds-payload-with-neutral-key-name"
|
||||
if err := ps.SetSecret(neutral, secret); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 磁盘上是密文
|
||||
var raw string
|
||||
if err := r.db.QueryRow(`SELECT value FROM config_demo3 WHERE key = ?`, neutral).Scan(&raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !security.IsEncrypted(raw) {
|
||||
t.Fatalf("SetSecret 应强制加密,实际 %q", raw)
|
||||
}
|
||||
// GetSecret 读回明文
|
||||
got, err := ps.GetSecret(neutral)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != secret {
|
||||
t.Fatalf("GetSecret 应返回明文,实际 %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 判据:**密钥未装配时 SetSecret 拒绝写入**(不静默存明文)。
|
||||
//
|
||||
// 这是最危险的静默降级:插件以为存了密文,实际磁盘上是明文。
|
||||
func TestSetSecretRefusesWithoutKey(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
security.ClearConfigCodec()
|
||||
defer testCodec(t) // 复原,避免影响其它判据
|
||||
|
||||
r := NewConfigRegistry(filepath.Join(dir, "c.db"))
|
||||
ps := r.PluginConfig("demo4")
|
||||
ps.RegisterDef(ConfigDef{Key: "enabled", Default: "1"})
|
||||
|
||||
err := ps.SetSecret("blob", "must-not-be-plain")
|
||||
if err == nil {
|
||||
t.Fatal("无密钥时 SetSecret 必须报错,不能静默写明文")
|
||||
}
|
||||
// 且确实没写进去
|
||||
var cnt int
|
||||
r.db.QueryRow(`SELECT COUNT(*) FROM config_demo4 WHERE key = 'blob'`).Scan(&cnt)
|
||||
if cnt != 0 {
|
||||
t.Error("拒绝写入后库里不应有该键")
|
||||
}
|
||||
// 空值是允许的(删除语义)
|
||||
if err := ps.SetSecret("blob", ""); err != nil {
|
||||
t.Errorf("空值应允许写入: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 判据:SetSecret 写入的值能被普通 Get 读到(两种读法互通,不产生孤岛)。
|
||||
func TestSetSecretReadableByGet(t *testing.T) {
|
||||
r := newSecReg(t)
|
||||
ps := r.PluginConfig("demo5")
|
||||
ps.RegisterDef(ConfigDef{Key: "enabled", Default: "1"})
|
||||
if err := ps.SetSecret("blob", "value-xyz-123456"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v, err := ps.Get("blob") // Get 会走 openFromStorage
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fmt.Sprint(v) != "value-xyz-123456" {
|
||||
t.Fatalf("Get 应能读到 SetSecret 写的值,实际 %v", v)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user