From e91ca913671a94c587261f8ee35040ab7aa9da43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=94=AF?= Date: Fri, 11 Sep 2026 00:41:59 +0800 Subject: [PATCH] =?UTF-8?q?fix(security):=20=E5=86=99=E5=85=A5=E4=BE=A7?= =?UTF-8?q?=E5=87=AD=E8=AF=81=E8=BF=87=E6=BB=A4=20=E2=80=94=20=E5=AF=86?= =?UTF-8?q?=E9=92=A5=E4=B8=8D=E5=86=8D=E8=BF=9B=E8=AE=B0=E5=BF=86/?= =?UTF-8?q?=E5=9B=BE=E8=B0=B1/Obsidian=20=E9=95=9C=E5=83=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景(2026-09-10 mc P0 事故):某轮蒸馏把含真 Tailscale 预授权 key 的原始对话 当事实入库 → 知识图谱按其文本建实体 → ObsidianSyncer 用实体标题当文件名/正文, 把 tskey-auth-… 落成可读镜像文件,又被 git 跟踪并推送 Gitea。 本提交在三个写入边界统一加脱敏。 新增 internal/redact(唯一真源): - SecretPattern 覆盖 sk- / tskey- / github_pat_ / ghp_ / nvapi- / AKIA - Go RE2 不支持 lookbehind,故"前一字符是否属于更长标识符"手工判定(isTokenByte) - sk- 段只吃 [A-Za-z0-9],避免误伤 URL 里的 task-driven 片段(事故中的假阳性来源) - RedactSecrets 幂等;ContainsSecret 供"直接丢弃"场景用 四处接入: - distill/quality.go IsQualityFact 判定前脱敏 + FilterQualityFacts 返回值脱敏 - governance/graph_auto.go cleanEntityName 命中→空串;UpdateFromDistill 只对有效实体 建节点/建边;extractEntitiesFromText 过滤;含凭证的 fact 不建节点 - api/routes/obsidian.go sanitizeFilename 入参脱敏 + PushToObsidian 镜像正文脱敏 - api/server.go 蒸馏直写记忆库路径(绕过 FilterQualityFacts 的那条)同步脱敏 测试:13 条新用例(redact 5 / distill 3 / governance 4 / routes 1), 含 URL 假阳性回归与幂等性断言。全部使用构造的假密钥,不含任何真实凭证。 证据:go build ./... OK; go test -count=1 ./internal/redact/ ./internal/distill/ ./internal/governance/ ./internal/api/routes/ 全绿。 顺带修既有 test 腐化(否则 governance 包根本无法编译测试,非本任务引入): governance_test.go isContradiction→IsContradiction、Navigate 补 relFilter 参数; bench_test.go 同。仅测试文件,无生产行为改动。 --- go/internal/api/routes/obsidian.go | 6 ++ go/internal/api/routes/obsidian_test.go | 16 +++++ go/internal/api/server.go | 4 ++ go/internal/distill/quality.go | 29 +++++--- go/internal/distill/quality_test.go | 57 ++++++++++++++-- go/internal/governance/bench_test.go | 6 +- go/internal/governance/governance_test.go | 10 +-- go/internal/governance/graph_auto.go | 39 +++++++++-- go/internal/governance/graph_auto_test.go | 82 +++++++++++++++++++++++ go/internal/redact/redact.go | 74 ++++++++++++++++++++ go/internal/redact/redact_test.go | 80 ++++++++++++++++++++++ 11 files changed, 372 insertions(+), 31 deletions(-) create mode 100644 go/internal/governance/graph_auto_test.go create mode 100644 go/internal/redact/redact.go create mode 100644 go/internal/redact/redact_test.go diff --git a/go/internal/api/routes/obsidian.go b/go/internal/api/routes/obsidian.go index fef71a1..4a36c7e 100644 --- a/go/internal/api/routes/obsidian.go +++ b/go/internal/api/routes/obsidian.go @@ -15,6 +15,7 @@ import ( "time" "unicode" + "github.com/xiaoxue/memoryweave/internal/redact" "github.com/xiaoxue/memoryweave/internal/storage" ) @@ -58,6 +59,9 @@ func (s *ObsidianSyncer) PushToObsidian(memories []map[string]interface{}, folde used := make(map[string]int, len(memories)) for _, mem := range memories { content := strVal(mem["content"]) + // 2026-09-10 P0:镜像正文同样脱敏——旧事故里正文与文件名都把 + // tskey-auth-… 原样落盘(小唯/07-Wiki/织忆/未找到命令.md)。 + content = redact.RedactSecrets(content) if len(content) < 5 { continue } @@ -228,6 +232,8 @@ func (s *ObsidianSyncer) StatusHandler(w http.ResponseWriter, r *http.Request) { // 现在只替换文件系统非法字符(/ \ : * ? " < > | 控制符等),连续的非法字符折叠成一个 '_'。 // 返回空串表示内容里没有任何可用的安全字符,由调用方兜底。 func sanitizeFilename(s string) string { + // 2026-09-10 P0:入参先脱敏,防任何路径把凭证带进文件名 + s = redact.RedactSecrets(s) var b strings.Builder prevIllegal := false for _, r := range s { diff --git a/go/internal/api/routes/obsidian_test.go b/go/internal/api/routes/obsidian_test.go index 9bd5383..e827a0a 100644 --- a/go/internal/api/routes/obsidian_test.go +++ b/go/internal/api/routes/obsidian_test.go @@ -164,3 +164,19 @@ func names(entries []os.DirEntry) []string { } return out } + +// ─── 2026-09-10 P0:文件名不得带凭证 ─────────────────────── + +func TestSanitizeFilename_RedactsSecret(t *testing.T) { + const fakeKey = "tskey-auth-kTESTONLY0000000000000000000000000000000000000" + got := sanitizeFilename("authkey " + fakeKey) + if got == "" { + t.Fatal("脱敏后不应为空(占位符仍可读)") + } + if strings.Contains(got, "tskey-auth-kTESTONLY") { + t.Errorf("文件名仍含凭证: %q", got) + } + if strings.Contains(got, "/") || strings.Contains(got, string(os.PathSeparator)) { + t.Errorf("文件名仍含路径分隔符: %q", got) + } +} diff --git a/go/internal/api/server.go b/go/internal/api/server.go index dcfd4da..bae8fcc 100644 --- a/go/internal/api/server.go +++ b/go/internal/api/server.go @@ -22,6 +22,7 @@ import ( "github.com/xiaoxue/memoryweave/internal/governance" "github.com/xiaoxue/memoryweave/internal/metrics" "github.com/xiaoxue/memoryweave/internal/models" + "github.com/xiaoxue/memoryweave/internal/redact" "github.com/xiaoxue/memoryweave/internal/selfoptimize" "github.com/xiaoxue/memoryweave/internal/storage" ) @@ -142,6 +143,9 @@ func NewServer() http.Handler { // 2026-09-07 方案B 质量门槛: 碎片(<20字)/噪声句(状态汇报/桥接/reflection)不入库, // 与已有记忆完全重复跳过(蒸馏直写不走 commit exact_dup, 需本层查重)。 for _, fact := range result.Facts { + // 2026-09-10 P0:直写路径同样脱敏(这里绕过 FilterQualityFacts, + // 事故里泄漏进镜像的记忆正是从这条路径入库的)。 + fact = redact.RedactSecrets(fact) if !distill.IsQualityFact(fact) { continue // 碎片/噪声过滤 } diff --git a/go/internal/distill/quality.go b/go/internal/distill/quality.go index d8afbe6..b696165 100644 --- a/go/internal/distill/quality.go +++ b/go/internal/distill/quality.go @@ -1,26 +1,34 @@ // 织忆 MemoryWeave — 蒸馏质量门槛(方案B 严格版, kanban t_cc07ef4b) // // 2026-09-07 t_cc07ef4b 继承 t_9316bf56 AC-1: LLM 提炼 fact 入库前过滤 -// 规则(按卡面 spec, 覆盖原 946f0c9 宽松版): -// - <20字 → 拒绝 (碎片; 与质量看门狗 FRAG_LEN=20 对齐, 无用户信号豁免) -// - 纯疑问句 → 拒绝 (OpenQuestions 合流 + LLM 直接输出问句) -// - 状态汇报型 → 拒绝 (健康检查/重启/验证/桥接/daemon reflection 类进程噪声) -// - 20-50字 → 需含实体或动词短语才入库 -// - >50字 → 通过 (除非命中上面 纯疑问/状态汇报 规则) +// +// 规则(按卡面 spec, 覆盖原 946f0c9 宽松版): +// - <20字 → 拒绝 (碎片; 与质量看门狗 FRAG_LEN=20 对齐, 无用户信号豁免) +// - 纯疑问句 → 拒绝 (OpenQuestions 合流 + LLM 直接输出问句) +// - 状态汇报型 → 拒绝 (健康检查/重启/验证/桥接/daemon reflection 类进程噪声) +// - 20-50字 → 需含实体或动词短语才入库 +// - >50字 → 通过 (除非命中上面 纯疑问/状态汇报 规则) +// // 与 LightMem"保留小细节"哲学差异: 原版允许 8-20 字带用户信号(如"用户喜欢喝咖啡") -// 保留——但看门狗把 <20 字全部计为碎片, AC-2(新增碎片率<10%)要求一律拒绝, -// 故此处 <20 字无豁免。短对话原始内容仍完整保留在 episodes 层, 不丢失信息。 +// +// 保留——但看门狗把 <20 字全部计为碎片, AC-2(新增碎片率<10%)要求一律拒绝, +// 故此处 <20 字无豁免。短对话原始内容仍完整保留在 episodes 层, 不丢失信息。 package distill import ( "strings" "unicode" "unicode/utf8" + + "github.com/xiaoxue/memoryweave/internal/redact" ) // IsQualityFact 判断蒸馏事实是否有入库价值(严格质量门槛) +// +// 2026-09-10 P0 追加:先做密钥脱敏再判定。含凭证的事实不再把原文带进图谱 +// /镜像(事故见 internal/redact 包注释)。脱敏后若只剩占位符(<20 字)自然被拒。 func IsQualityFact(fact string) bool { - s := strings.TrimSpace(fact) + s := strings.TrimSpace(redact.RedactSecrets(fact)) if s == "" { return false } @@ -47,9 +55,12 @@ func IsQualityFact(fact string) bool { } // FilterQualityFacts 过滤事实列表, 返回通过质量门槛的子集(引擎入队后统一调用) +// +// 2026-09-10 P0:返回值已做密钥脱敏(调用方沿用返回值即可,勿再用原始 slice)。 func FilterQualityFacts(facts []string) []string { out := make([]string, 0, len(facts)) for _, f := range facts { + f = redact.RedactSecrets(f) if IsQualityFact(f) { out = append(out, f) } diff --git a/go/internal/distill/quality_test.go b/go/internal/distill/quality_test.go index f2176e4..b201676 100644 --- a/go/internal/distill/quality_test.go +++ b/go/internal/distill/quality_test.go @@ -1,6 +1,9 @@ package distill -import "testing" +import ( + "strings" + "testing" +) // 质量门槛单测 (kanban t_cc07ef4b 继承 t_9316bf56 AC-1) // 规则: @@ -48,7 +51,7 @@ func TestIsQualityFact_PureQuestionRejected(t *testing.T) { {"怎么开头", "怎么解决这个报错问题呢", false}, {"是否开头无标点", "是否应该把模型切换到本地", false}, {"转述疑问句(带主语,陈述)", "用户询问了系统是否可以升级到最新稳定版本", true}, // 20字 主语转述非纯问句 - {"正常陈述带吗字(句中)", "用户说这个报错不用再管它了因为已经处理过了", true}, // 21字, 有主语+动词 + {"正常陈述带吗字(句中)", "用户说这个报错不用再管它了因为已经处理过了", true}, // 21字, 有主语+动词 } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -70,7 +73,7 @@ func TestIsQualityFact_StatusReportRejected(t *testing.T) { {"桥接噪声", "小唯a06与all桥接状态同步完成", false}, {"重启完成无主", "重启完成,服务已恢复运行", false}, {"带主语重启(真事实)", "用户昨天重启了家里的服务器并恢复了所有服务", true}, // 21字 有主语+实体服务器 - {"带主语升级", "小唯昨天将织忆系统升级到了新版本并验证通过", true}, // 有主语 + {"带主语升级", "小唯昨天将织忆系统升级到了新版本并验证通过", true}, // 有主语 } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -88,7 +91,7 @@ func TestIsQualityFact_MidLengthNeedsEntityOrVerb(t *testing.T) { want bool }{ // 20-50字 无实体无动词 → 拒绝 - {"纯形容词堆叠", "很好很好很好很好很好很好很好很好很好", false}, // 20字 无实体无动词 + {"纯形容词堆叠", "很好很好很好很好很好很好很好很好很好", false}, // 20字 无实体无动词 {"无实义名词串", "关于这个系统的一些非常详细的说明文档内容汇总介绍", false}, // 24字 无实体无动词 // 20-50字 含实体 → 通过 {"含织忆实体", "用户对织忆系统的蒸馏质量提出了改进要求并希望尽快处理", true}, @@ -111,9 +114,9 @@ func TestIsQualityFact_MidLengthNeedsEntityOrVerb(t *testing.T) { func TestFilterQualityFacts(t *testing.T) { in := []string{ - "重启系统", // <20 拒 - "为什么系统会重启?", // 疑问 拒 - "健康检查完成", // 状态 拒 + "重启系统", // <20 拒 + "为什么系统会重启?", // 疑问 拒 + "健康检查完成", // 状态 拒 "用户对织忆系统提出了新的功能需求希望尽快实现", // 22字 实体 通过 } got := FilterQualityFacts(in) @@ -124,3 +127,43 @@ func TestFilterQualityFacts(t *testing.T) { t.Errorf("FilterQualityFacts kept %q, want %q", got[0], in[3]) } } + +// ─── 2026-09-10 P0:凭证不得原样进入记忆/图谱 ─────────────── + +const fakeSecretFact = "tskey-auth-kTESTONLY0000000000000000000000000000000000000000" + +func TestFilterQualityFacts_RedactsSecrets(t *testing.T) { + facts := []string{ + "tailscale 预授权 key " + fakeSecretFact + " 已写进启动脚本用于远程接入", + "牧尘偏好结论先行,不喜欢废话科普与背景铺垫", + } + out := FilterQualityFacts(facts) + if len(out) != 2 { + t.Fatalf("期望 2 条通过,得到 %d: %v", len(out), out) + } + for _, f := range out { + if strings.Contains(f, fakeSecretFact) { + t.Errorf("输出仍含完整密钥: %q", f) + } + if strings.Contains(f, "tskey-auth-kTESTONLY") { + t.Errorf("输出仍含凭证前缀: %q", f) + } + } + if !strings.Contains(out[0], "") { + t.Errorf("期望占位符,得到 %q", out[0]) + } +} + +func TestIsQualityFact_SecretOnlyRejected(t *testing.T) { + if IsQualityFact(fakeSecretFact) { + t.Error("纯凭证事实脱敏后不足 20 字,应被拒绝") + } +} + +func TestFilterQualityFacts_KeepsURLUntouched(t *testing.T) { + in := "参考 https://yoheinakajima.com/task-driven-autonomous-agents 项目的 Agent 编排设计思路" + out := FilterQualityFacts([]string{in}) + if len(out) != 1 || out[0] != in { + t.Errorf("URL 文本被误改: %v", out) + } +} diff --git a/go/internal/governance/bench_test.go b/go/internal/governance/bench_test.go index 441a95e..6c7c722 100644 --- a/go/internal/governance/bench_test.go +++ b/go/internal/governance/bench_test.go @@ -110,7 +110,7 @@ func BenchmarkGraph_Navigate_5Hops(b *testing.B) { g := buildScaleGraph(200, 3) b.ResetTimer() for i := 0; i < b.N; i++ { - g.Navigate(fmt.Sprintf("n-%d", i%200), 5, "shared") + g.Navigate(fmt.Sprintf("n-%d", i%200), 5, "shared", nil) } } @@ -118,7 +118,7 @@ func BenchmarkGraph_Navigate_Deep(b *testing.B) { g := buildScaleGraph(500, 2) b.ResetTimer() for i := 0; i < b.N; i++ { - g.Navigate("n-0", 10, "shared") + g.Navigate("n-0", 10, "shared", nil) } } @@ -126,7 +126,7 @@ func BenchmarkGraph_Navigate_LargeScale(b *testing.B) { g := buildScaleGraph(2000, 3) b.ResetTimer() for i := 0; i < b.N; i++ { - g.Navigate(fmt.Sprintf("n-%d", i%2000), 3, "shared") + g.Navigate(fmt.Sprintf("n-%d", i%2000), 3, "shared", nil) } } diff --git a/go/internal/governance/governance_test.go b/go/internal/governance/governance_test.go index 5b7cbc3..59b893a 100644 --- a/go/internal/governance/governance_test.go +++ b/go/internal/governance/governance_test.go @@ -135,7 +135,7 @@ func TestInMemoryGraph_Navigate(t *testing.T) { g.AddEdge("e1", "n1", "n2", "used_by", "shared", 1.0) g.AddEdge("e2", "n2", "n3", "connects_to", "shared", 0.8) - paths, err := g.Navigate("n1", 2, "shared") + paths, err := g.Navigate("n1", 2, "shared", nil) if err != nil { t.Fatalf("navigate failed: %v", err) } @@ -170,12 +170,12 @@ func TestInMemoryGraph_NamespaceIsolation(t *testing.T) { g.AddNode("n2", "B", "type", "hermes") g.AddEdge("e1", "n1", "n2", "r", "hermes", 1.0) - paths, _ := g.Navigate("n1", 2, "shared") + paths, _ := g.Navigate("n1", 2, "shared", nil) if len(paths) > 0 { t.Error("shared namespace should NOT see hermes-only edges") } - paths2, _ := g.Navigate("n1", 2, "hermes") + paths2, _ := g.Navigate("n1", 2, "hermes", nil) if len(paths2) == 0 { t.Error("hermes namespace should see its edges") } @@ -203,7 +203,7 @@ func Test_isContradiction(t *testing.T) { {"config updated", "config not updated", true}, } for _, tc := range tests { - got := isContradiction(tc.a, tc.b) + got := IsContradiction(tc.a, tc.b) if got != tc.expect { t.Errorf("isContradiction(%q, %q) = %v, want %v", tc.a, tc.b, got, tc.expect) } @@ -231,6 +231,6 @@ func BenchmarkGraphNavigate(b *testing.B) { } b.ResetTimer() for i := 0; i < b.N; i++ { - g.Navigate("na", 2, "s") + g.Navigate("na", 2, "s", nil) } } diff --git a/go/internal/governance/graph_auto.go b/go/internal/governance/graph_auto.go index d2fa49f..df8570e 100644 --- a/go/internal/governance/graph_auto.go +++ b/go/internal/governance/graph_auto.go @@ -6,6 +6,8 @@ import ( "strings" "time" "unicode" + + "github.com/xiaoxue/memoryweave/internal/redact" ) // AutoGraphUpdater 自动维护知识图谱 @@ -19,23 +21,34 @@ func NewAutoGraphUpdater(g GraphStore) *AutoGraphUpdater { // UpdateFromDistill 从蒸馏产物自动更新图谱(§3.4) func (agu *AutoGraphUpdater) UpdateFromDistill(distilled *DistillInput) { - // 1. 提取实体并创建节点(ID 和 name 都清洗) + // 0. 密钥过滤(2026-09-10 P0,见 internal/redact):含凭证形状的实体不进图, + // 否则实体名会被 ObsidianSync 当文件名,把密钥落成可读镜像文件 + // (实例:小唯/07-Wiki/织忆/未找到命令.md 的文件名与正文含 tskey-auth-…)。 + validEnts := make([]string, 0, len(distilled.Entities)) for _, entity := range distilled.Entities { + if redact.ContainsSecret(entity) || cleanEntityName(entity) == "" { + continue + } + validEnts = append(validEnts, entity) + } + + // 1. 提取实体并创建节点(ID 和 name 都清洗) + for _, entity := range validEnts { nodeID := entityID(entity) cleanName := cleanEntityName(entity) agu.graph.AddNode(nodeID, cleanName, detectNodeType(entity), distilled.Namespace) } // 2. 创建实体间关系 + CO_OCCURS 共访边 - entityCount := len(distilled.Entities) + entityCount := len(validEnts) for i := 0; i < entityCount; i++ { for j := i + 1; j < entityCount; j++ { - eidI := entityID(distilled.Entities[i]) - eidJ := entityID(distilled.Entities[j]) + eidI := entityID(validEnts[i]) + eidJ := entityID(validEnts[j]) // 2a. 语义关系边(inferRelation) edgeID := fmt.Sprintf("e_%s_%s_%d", eidI, eidJ, time.Now().UnixNano()) - relation := inferRelation(distilled.Entities[i], distilled.Entities[j], distilled.Content) + relation := inferRelation(validEnts[i], validEnts[j], distilled.Content) agu.graph.AddEdge(edgeID, eidI, eidJ, relation, distilled.Namespace, 0.5) @@ -69,13 +82,16 @@ func (agu *AutoGraphUpdater) UpdateFromDistill(distilled *DistillInput) { // 4. DERIVED_FROM 边:蒸馏产物 → 原始 episode if distilled.EpisodeID != "" { - for _, entity := range distilled.Entities { + for _, entity := range validEnts { eid := entityID(entity) derivedEdgeID := fmt.Sprintf("df_%s_%s_%d", eid, distilled.EpisodeID, time.Now().UnixNano()) agu.graph.AddEdge(derivedEdgeID, eid, distilled.EpisodeID, "DERIVED_FROM", distilled.Namespace, 0.9) } for _, fact := range distilled.Facts { + if redact.ContainsSecret(fact) { + continue // 含凭证的事实不建节点(2026-09-10 P0) + } factNodeID := "f_" + strings.ReplaceAll(entityID(fact), "n_", "") derivedEdgeID := fmt.Sprintf("df_%s_%s_%d", factNodeID, distilled.EpisodeID, time.Now().UnixNano()) agu.graph.AddEdge(derivedEdgeID, factNodeID, distilled.EpisodeID, @@ -146,6 +162,10 @@ func cleanEntityName(raw string) string { if clean == "" { clean = "unknown" } + // 含凭证形状 → 返回空串,调用方 skip(2026-09-10 P0) + if redact.ContainsSecret(clean) { + return "" + } return clean } @@ -181,6 +201,9 @@ func extractEntitiesFromText(text string) []string { var entities []string for _, w := range words { if len(w) > 1 && (w[0] >= 'A' && w[0] <= 'Z') { + if redact.ContainsSecret(w) { + continue // 2026-09-10 P0:凭证形状的 token 不当实体 + } entities = append(entities, w) } } @@ -188,7 +211,9 @@ func extractEntitiesFromText(text string) []string { } func minz(a, b int) int { - if a < b { return a } + if a < b { + return a + } return b } diff --git a/go/internal/governance/graph_auto_test.go b/go/internal/governance/graph_auto_test.go new file mode 100644 index 0000000..03aadd8 --- /dev/null +++ b/go/internal/governance/graph_auto_test.go @@ -0,0 +1,82 @@ +// 织忆 MemoryWeave — 图谱写入侧密钥过滤单元测试 +// 2026-09-10 新增(mc P0 事故):实体名含凭证时不得建节点/建边, +// 否则 ObsidianSync 会拿实体标题当文件名把密钥落成镜像。 +package governance + +import ( + "strings" + "testing" +) + +// 测试用假密钥(非真实凭证) +const fakeSecretEntity = "tskey-auth-kTESTONLY0000000000000000000000000000000000000000" + +func TestCleanEntityName_DropsSecretShaped(t *testing.T) { + if got := cleanEntityName(fakeSecretEntity); got != "" { + t.Errorf("含凭证的实体名应返回空串,得到 %q", got) + } + if got := cleanEntityName("key=sk-TESTONLY000000000000000000000000000"); got != "" { + t.Errorf("含 sk- 凭证的实体名应返回空串,得到 %q", got) + } +} + +func TestCleanEntityName_KeepsNormalUnicode(t *testing.T) { + for _, in := range []string{"牧尘", "织忆 MemoryWeave", "PostgreSQL", "192.168.123.11"} { + got := cleanEntityName(in) + if got == "" { + t.Errorf("正常实体 %q 不应被丢弃", in) + } + if strings.Contains(got, "REDACTED") { + t.Errorf("正常实体 %q 被误脱敏为 %q", in, got) + } + } +} + +func TestExtractEntitiesFromText_SkipsSecret(t *testing.T) { + // extractEntitiesFromText 只收大写开头的 token,凭证行需以大写引入才可能被收 + text := "TsKey " + fakeSecretEntity + " Docker Nginx" + got := extractEntitiesFromText(text) + for _, e := range got { + if strings.Contains(e, "tskey-auth") { + t.Errorf("凭证形状的 token 不应成为实体: %q", e) + } + } +} + +func TestUpdateFromDistill_NoNodeForSecretEntity(t *testing.T) { + g := NewInMemoryGraph() + up := NewAutoGraphUpdater(g) + up.UpdateFromDistill(&DistillInput{ + EpisodeID: "ep_test_1", + Content: "配置 tailscale", + Facts: []string{"Tailscale 预授权 key 已写入配置文件并完成节点加入"}, + Entities: []string{"Docker", fakeSecretEntity}, + Namespace: "ns_test", + }) + + nodes := g.ListNodes("ns_test") + if len(nodes) == 0 { + t.Fatal("正常实体 Docker 应建出节点,实际 0 个节点") + } + for _, n := range nodes { + name, _ := n["name"].(string) + if strings.Contains(name, "tskey-auth") { + t.Errorf("凭证实体不该建节点,却出现: %q", name) + } + } + found := false + for _, n := range nodes { + if n["name"] == "Docker" { + found = true + } + } + if !found { + t.Errorf("正常实体 Docker 应保留,实际节点: %v", nodes) + } + // 边也不该引用凭证实体 + for _, e := range g.ListNodes("") { + if strings.Contains(e["id"].(string), "tskey-auth") { + t.Errorf("凭证实体不该出现在边端点: %v", e) + } + } +} diff --git a/go/internal/redact/redact.go b/go/internal/redact/redact.go new file mode 100644 index 0000000..50a42af --- /dev/null +++ b/go/internal/redact/redact.go @@ -0,0 +1,74 @@ +// Package redact —— 密钥脱敏唯一真源(2026-09-10 P0 事故后固化) +// +// 事故背景:某轮蒸馏把含真密钥的原始对话当事实入库 → 知识图谱按该文本建实体 +// → ObsidianSyncer.sanitizeFilename 用实体标题当文件名,于是 +// `tskey-auth-kzu…` 被写进镜像文件名与正文(实例:小唯/07-Wiki/织忆/未找到命令.md)。 +// 该 vault 又被 git 跟踪并推送 Gitea,形成凭证泄露面。 +// +// 本包提供内容侧唯一真源,供三处共用: +// - distill 质量门槛(事实入库前) +// - governance 图谱实体名清洗(建节点/建边前) +// - api/routes Obsidian 文件名 sanitize(落盘前) +package redact + +import ( + "regexp" + "strings" +) + +// SecretPattern 匹配常见凭证形状。 +// +// 注意:Go RE2 不支持 lookbehind,故"前一字符是否属于更长标识符"的判定 +// 在 RedactSecrets/ContainsSecret 里手工做(见 isTokenByte)。 +// `sk-` 段故意只吃 [A-Za-z0-9],避免误伤 URL 片段 +// (如 https://a.com/task-driven-autonomous-agents 里的 "sk-driven…")。 +var SecretPattern = regexp.MustCompile( + `sk-[A-Za-z0-9]{24,}` + // OpenAI / DeepSeek / Agnes / NewAPI 系 + `|tskey-[A-Za-z0-9_-]{20,}` + // Tailscale 预授权 key + `|github_pat_[A-Za-z0-9_]{20,}` + // GitHub fine-grained PAT + `|ghp_[A-Za-z0-9]{30,}` + // GitHub classic PAT + `|nvapi-[A-Za-z0-9_-]{20,}` + // NVIDIA NIM + `|AKIA[0-9A-Z]{16}`) // AWS access key id + +// Placeholder 脱敏后的替换文本。 +const Placeholder = "" + +// isTokenByte 判断字节是否可能属于一个更长 token(用于剔除嵌在标识符里的假命中)。 +func isTokenByte(c byte) bool { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || + c >= '0' && c <= '9' || c == '_' || c == '-' +} + +// RedactSecrets 把文本里所有凭证形状替换为 Placeholder;无命中时原样返回。 +func RedactSecrets(s string) string { + idx := SecretPattern.FindAllStringIndex(s, -1) + if len(idx) == 0 { + return s + } + var b strings.Builder + last := 0 + for _, m := range idx { + start, end := m[0], m[1] + if start > 0 && isTokenByte(s[start-1]) { + continue // 前一位是单词字符 → 属于更长标识符,不替换 + } + b.WriteString(s[last:start]) + b.WriteString(Placeholder) + last = end + } + if last == 0 { + return s // 全部命中都被判为假阳性 + } + b.WriteString(s[last:]) + return b.String() +} + +// ContainsSecret 判断文本是否含真凭证形状(用于实体名/标题直接丢弃的场景)。 +func ContainsSecret(s string) bool { + for _, m := range SecretPattern.FindAllStringIndex(s, -1) { + if m[0] == 0 || !isTokenByte(s[m[0]-1]) { + return true + } + } + return false +} diff --git a/go/internal/redact/redact_test.go b/go/internal/redact/redact_test.go new file mode 100644 index 0000000..5f8c585 --- /dev/null +++ b/go/internal/redact/redact_test.go @@ -0,0 +1,80 @@ +// 织忆 MemoryWeave — 凭证脱敏单元测试 +// 2026-09-10 新增(mc P0 事故):锁死「密钥不得进记忆/图谱/Obsidian 镜像」这个回归。 +package redact + +import ( + "strings" + "testing" +) + +// 测试用假密钥(非真实凭证,按各平台形状构造) +const ( + fakeTailscale = "tskey-auth-kTESTONLY0000000000000000000000000000000000000000000000000" // 61 位 + fakeOpenAI = "sk-TESTONLY000000000000000000000000000" // 48 位 + fakeGithubPAT = "github_pat_11TESTONLY0000000000000000000000000000000000000000000000000000000000000000" + fakeNvapi = "nvapi-TESTONLY0000000000000000000000000000" +) + +func TestRedactSecrets_KnownShapes(t *testing.T) { + cases := []struct { + name string + in string + }{ + {"tailscale", "配置 tailscale up --authkey " + fakeTailscale + " 完成"}, + {"openai", "OPENAI_API_KEY=" + fakeOpenAI}, + {"github_pat", "GITHUB_PERSONAL_ACCESS_TOKEN: " + fakeGithubPAT}, + {"nvapi", "key=" + fakeNvapi}, + {"aws", "AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE"}, + } + for _, tc := range cases { + got := RedactSecrets(tc.in) + if strings.Contains(got, "") != true { + t.Errorf("%s: 未脱敏: %q", tc.name, got) + } + } + // 脱敏后不得再残留任何形状 + for _, tc := range cases { + if ContainsSecret(RedactSecrets(tc.in)) { + t.Errorf("%s: 脱敏后仍能匹配到凭证形状", tc.name) + } + } +} + +// URL / 普通连字符词里的 "sk-" 片段不得误伤(事故里 false positive 的来源) +func TestRedactSecrets_NoFalsePositiveOnURL(t *testing.T) { + in := "参考 https://yoheinakajima.com/task-driven-autonomous-agents 与 babybeeagi-task-xxx 的说明" + if got := RedactSecrets(in); got != in { + t.Errorf("URL 片段被误脱敏:\n got=%q\nwant=%q", got, in) + } + if ContainsSecret(in) { + t.Error("ContainsSecret 对 URL 片段误报") + } +} + +// 嵌在更长标识符里的假命中不替换(前一位是单词字符) +func TestRedactSecrets_EmbeddedTokenIgnored(t *testing.T) { + in := "字段名 xxxkey_sk-TESTONLY0000000000000000000000000001234 不是凭证" + if got := RedactSecrets(in); got != in { + t.Errorf("嵌在标识符里的 token 被误脱敏: %q", got) + } +} + +func TestRedactSecrets_IdempotentAndPlainTextUntouched(t *testing.T) { + plain := "牧尘喜欢结论先行,不要废话科普。" + if got := RedactSecrets(plain); got != plain { + t.Errorf("纯文本被改动: %q", got) + } + once := RedactSecrets("key=" + fakeOpenAI) + if twice := RedactSecrets(once); twice != once { + t.Errorf("脱敏不幂等: %q → %q", once, twice) + } +} + +func TestContainsSecret(t *testing.T) { + if !ContainsSecret("authkey " + fakeTailscale) { + t.Error("真实形状应被判为含凭证") + } + if ContainsSecret("普通的记忆内容,没有凭证") { + t.Error("普通内容误报") + } +}