Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Reject stale document paths before rebuilding parents https://github.com/siyuan-note/siyuan/issues/19336

Daniel3b338bfdef2e
diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.go
index 2558ab000b..ed53f1fc0f 100644
--- a/kernel/filesys/tree.go
+++ b/kernel/filesys/tree.go
@@ -182,12 +182,16 @@ func LoadTreeWithFix(boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, n
defer releaseCryptoLease()
rootID := util.GetTreeID(p)
+ filePath := filepath.Join(util.DataDir, boxID, p)
if raw, ok := cache.GetTreeDataInBox(rootID, boxID); ok {
+ // 内容缓存不代表请求路径仍然有效,移动或删除后的旧路径不能触发补树。
+ if err = checkTreeFile(filePath); err != nil {
+ return
+ }
ret, err = LoadTreeByData(raw, boxID, p, luteEngine)
return
}
- filePath := filepath.Join(util.DataDir, boxID, p)
data, err := filelock.ReadFile(filePath)
if nil != err {
if !os.IsNotExist(err) {
@@ -273,12 +277,20 @@ func LoadTreeByData(data []byte, boxID, p string, luteEngine *lute.Lute) (ret *p
parentPath := parentAbsPath
parentAbsPath = filepath.Join(util.DataDir, boxID, parentAbsPath)
- parentDocIAL := DocIAL(parentAbsPath)
- if 1 > len(parentDocIAL) {
+ parentDocIAL, parentErr := readParentDocIAL(parentAbsPath)
+ if parentErr != nil && !errors.Is(parentErr, os.ErrNotExist) {
+ return nil, parentErr
+ }
+ if errors.Is(parentErr, os.ErrNotExist) {
+ // 直接解析数据的调用也必须确认子文档仍在磁盘上,避免旧数据重建已删除的父链。
+ if err = checkTreeFile(filepath.Join(util.DataDir, boxID, p)); err != nil {
+ return nil, err
+ }
// 子文档缺失父文档时自动补全 https://github.com/siyuan-note/siyuan/issues/7376
parentTree := treenode.NewTree(boxID, parentPath, hPathBuilder.String()+"Untitled", "Untitled")
if _, writeErr := WriteTree(parentTree); nil != writeErr {
logging.LogErrorf("rebuild parent tree [%s] failed: %s", parentAbsPath, writeErr)
+ return nil, writeErr
} else {
logging.LogInfof("rebuilt parent tree [%s]", parentAbsPath)
treenode.UpsertBlockTree(parentTree)
@@ -300,6 +312,52 @@ func LoadTreeByData(data []byte, boxID, p string, luteEngine *lute.Lute) (ret *p
return
}
+func checkTreeFile(absPath string) error {
+ info, err := os.Stat(absPath)
+ if err != nil {
+ return err
+ }
+ if !info.Mode().IsRegular() {
+ return fmt.Errorf("invalid document file [%s]", absPath)
+ }
+ return nil
+}
+
+// readParentDocIAL 区分父文档缺失与读取、认证、解析失败,只有缺失才允许补树。
+func readParentDocIAL(absPath string) (map[string]string, error) {
+ boxID := docIALBoxID(absPath)
+ dek, _, release, err := acquireCryptoLease(boxID)
+ if err != nil {
+ return nil, err
+ }
+ defer release()
+ data, err := filelock.ReadFile(absPath)
+ if err != nil {
+ return nil, err
+ }
+ relPath, err := filepath.Rel(filepath.Join(util.DataDir, boxID), absPath)
+ if err != nil {
+ return nil, err
+ }
+ data, err = decryptDataWithDEK(boxID, filepath.ToSlash(relPath), data, dek)
+ if err != nil {
+ return nil, err
+ }
+ var doc struct {
+ Properties map[string]string
+ }
+ if err = json.Unmarshal(data, &doc); err != nil {
+ return nil, fmt.Errorf("parse parent document [%s]: %w", absPath, err)
+ }
+ if len(doc.Properties) == 0 {
+ return nil, fmt.Errorf("missing parent document properties [%s]", absPath)
+ }
+ for key, value := range doc.Properties {
+ doc.Properties[key] = html.UnescapeAttrVal(value)
+ }
+ return doc.Properties, nil
+}
+
func DocIAL(absPath string) (ret map[string]string) {
// 加密笔记本的 .sy 是密文,流式 jsoniter 解析无法处理,需先整体读+解密。
// 反推 boxID:路径形如 <DataDir>/<boxID>/...;非加密笔记本走原流式逻辑。
@@ -323,8 +381,7 @@ func DocIAL(absPath string) (ret map[string]string) {
relPath := filepath.ToSlash(strings.TrimPrefix(absPath, filepath.Join(util.DataDir, boxID)+string(os.PathSeparator)))
plain, decErr := decryptDataWithDEK(boxID, relPath, raw, dek)
if decErr != nil {
- // 解密失败(可能文件损坏或密钥不匹配):返回空 map 而非 nil,
- // 避免 LoadTreeByData 的父文档补全逻辑把 nil 误判为"文档缺失"而凭空创建文档
+ // 属性查询不返回未认证的数据;需要区分缺失与错误的补树流程使用 readParentDocIAL。
logging.LogErrorf("decrypt doc [%s] for IAL failed: %s", absPath, decErr)
return map[string]string{}
}
diff --git a/kernel/filesys/tree_stale_path_test.go b/kernel/filesys/tree_stale_path_test.go
new file mode 100644
index 0000000000..4808815e58
--- /dev/null
+++ b/kernel/filesys/tree_stale_path_test.go
@@ -0,0 +1,167 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package filesys
+
+import (
+ "bytes"
+ "database/sql"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/88250/lute/render"
+ "github.com/mattn/go-sqlite3"
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func setupStalePathTest(t *testing.T) (string, string, string, []byte) {
+ t.Helper()
+ original := util.DataDir
+ util.DataDir = t.TempDir()
+ cache.ClearTreeCache()
+ t.Cleanup(func() {
+ cache.ClearTreeCache()
+ util.DataDir = original
+ })
+ box := "20260912000000-box0001"
+ parent := "20260912000001-parent1"
+ id := "20260912000002-child01"
+ p := "/" + parent + "/" + id + ".sy"
+ tree := treenode.NewTree(box, p, "/Parent/Child", "Child")
+ data := render.NewJSONRenderer(tree, util.NewLute().RenderOptions, util.NewLute().ParseOptions).Render()
+ return box, parent, p, data
+}
+
+func writeStalePathFixture(t *testing.T, box, p string, data []byte) string {
+ t.Helper()
+ abs := filepath.Join(util.DataDir, box, p)
+ if err := os.MkdirAll(filepath.Dir(abs), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(abs, data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ return abs
+}
+
+func TestLoadTreeRejectsStaleCachedPath(t *testing.T) {
+ for _, cached := range []bool{false, true} {
+ t.Run(map[bool]string{false: "disk", true: "cache"}[cached], func(t *testing.T) {
+ box, parent, p, data := setupStalePathTest(t)
+ oldPath := writeStalePathFixture(t, box, p, data)
+ newPath := "/" + filepath.Base(p)
+ newAbs := filepath.Join(util.DataDir, box, newPath)
+ if err := os.Rename(oldPath, newAbs); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(filepath.Dir(oldPath)); err != nil {
+ t.Fatal(err)
+ }
+ if cached {
+ id := util.GetTreeID(p)
+ cache.SetTreeDataInBox(id, box, data)
+ deadline := time.Now().Add(time.Second)
+ for {
+ if _, ok := cache.GetTreeDataInBox(id, box); ok {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("cache entry was not published")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ }
+ if _, err := LoadTree(box, p, util.NewLute()); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("expected missing old path, got %v", err)
+ }
+ if _, err := LoadTreeByData(data, box, p, util.NewLute()); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("expected stale data to reject parent repair, got %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(util.DataDir, box, parent+".sy")); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("old parent was restored: %v", err)
+ }
+ if _, err := LoadTree(box, newPath, util.NewLute()); err != nil {
+ t.Fatalf("new path without blocktree must load: %v", err)
+ }
+ got, err := os.ReadFile(newAbs)
+ if err != nil || !bytes.Equal(got, data) {
+ t.Fatalf("new document changed: %v", err)
+ }
+ })
+ }
+}
+
+func TestLoadTreePreservesInvalidParent(t *testing.T) {
+ for _, invalid := range []string{"{", "{}", `{"Properties":{}}`, `{"Properties":{"title":"Parent"},"Children":[`} {
+ t.Run(invalid, func(t *testing.T) {
+ box, parent, p, data := setupStalePathTest(t)
+ writeStalePathFixture(t, box, p, data)
+ parentAbs := writeStalePathFixture(t, box, parent+".sy", []byte(invalid))
+ if _, err := LoadTree(box, p, util.NewLute()); err == nil {
+ t.Fatal("expected invalid parent error")
+ }
+ got, err := os.ReadFile(parentAbs)
+ if err != nil || string(got) != invalid {
+ t.Fatalf("invalid parent was overwritten: %v", err)
+ }
+ })
+ }
+}
+
+func TestLoadTreeRepairsMissingParent(t *testing.T) {
+ box, parent, p, data := setupStalePathTest(t)
+ if !slices.Contains(sql.Drivers(), "sqlite3_extended") {
+ sql.Register("sqlite3_extended", &sqlite3.SQLiteDriver{})
+ }
+ originalDB := util.BlockTreeDBPath
+ util.BlockTreeDBPath = filepath.Join(t.TempDir(), "blocktree.db")
+ treenode.InitBlockTree(true)
+ t.Cleanup(func() {
+ treenode.CloseDatabase()
+ util.BlockTreeDBPath = originalDB
+ })
+ writeStalePathFixture(t, box, p, data)
+ if _, err := LoadTree(box, p, util.NewLute()); err != nil {
+ t.Fatal(err)
+ }
+ ial, err := readParentDocIAL(filepath.Join(util.DataDir, box, parent+".sy"))
+ if err != nil || ial["title"] != "Untitled" {
+ t.Fatalf("missing parent was not repaired: %v, %v", ial, err)
+ }
+}
+
+func TestLoadTreePreservesUnauthenticatedParent(t *testing.T) {
+ box, parent, p, data := setupStalePathTest(t)
+ originalProvider := DEKProvider
+ DEKProvider = func(string) ([]byte, error) { return bytes.Repeat([]byte{1}, 32), nil }
+ t.Cleanup(func() { DEKProvider = originalProvider })
+ encrypted, err := encryptDataWithDEK(box, p, data, bytes.Repeat([]byte{1}, 32))
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeStalePathFixture(t, box, p, encrypted)
+ parentPath := parent + ".sy"
+ parentData, err := encryptDataWithDEK(box, parentPath, []byte(`{"Properties":{"title":"Parent"}}`), bytes.Repeat([]byte{2}, 32))
+ if err != nil {
+ t.Fatal(err)
+ }
+ parentAbs := writeStalePathFixture(t, box, parentPath, parentData)
+ if _, err = LoadTree(box, p, util.NewLute()); err == nil {
+ t.Fatal("expected parent authentication failure")
+ }
+ got, err := os.ReadFile(parentAbs)
+ if err != nil || !bytes.Equal(got, parentData) {
+ t.Fatalf("unauthenticated parent was overwritten: %v", err)
+ }
+}